I have a code:
enter image description here
When I use flickity, I try using event “mousedown” for “.flickity-viewport”, it doesn’t work for left click. Please help me? Thanhks
Category: javascript
Category Added in a WPeMatico Campaign
Vue Slick Carousel
I have slider with VueSlickCarousel.
I want to be able to manually change the pagination during the scrolling, not after it.
data() {
return {
sliderConfig: {
arrows: false,
dots: true,
infinite: true,
slidesToShow: 2,
slidesToScroll: 1,
responsive: [
{
breakpoint: 1023,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
}
},
],
autoplay: true,
autoplaySpeed: 2000,
speed: 6000,
cssEase: 'ease',
}
}
}
e.stopPropagation() on click event
Please tell me why the e.stopPropagation()
function does not work?
$(document).on("click", ".el", function(e) {
e.stopPropagation();
alert(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="el" onclick="alert(1)";>Click</div>
Close-On-Click-Away not working when MUI custom field is inside component
In my React component I have a sidebar menu, CustomizeComponentSidebar
that in turn contains several other custom html tags. One of them is MUI’s Multiple Select. I made a close-on-click-outside functionality for using useRef
. Everything is fine except if I click on MUI’s Multiple Select field, it traces the click as outside the component and closes it. I also tried using MUI’s ClickAwayListener instead, with the same result. Any help appreciated
const handleClickOutside = (event) =>
ref.current && !ref.current.contains(event.target) && resetSidebar();
useEffect(
() => {
document.addEventListener("click", handleClickOutside, true);
return () => document
.removeEventListener("click", handleClickOutside, true);
},
[customizeComponentMenu.open]
);
……..
<div ref={ ref } className="position-absolute">
<CustomizeComponentSidebar
props={ props }
/>
</div>
///SelectField looks like this
return (
<div>
<FormControl sx={ { m: 1, width: 300 } }>
<InputLabel id="demo-multiple-name-label">Select</InputLabel>
<Select
labelId="demo-multiple-name-label"
id="demo-multiple-name"
multiple={ props.configuration.multipleOptions }
value={ getValue() }
onChange={ handleChange }
input={ <OutlinedInput label="Option" /> }
MenuProps={ MenuProps }
>
{ options.map((option) =>
(
<MenuItem
key={ option }
value={ option }
style={ getStyles(option, optionName, theme) }
>
{ option }
</MenuItem>
))
}
</Select>
</FormControl>
</div>
);
};
export default SelectField;
Align Label To Top Off Drop Down Selector Box – Woocommerce
Thank you for taking the time to read this. I need to align the label of the variation section to the top before the variation drop down selector box starts, as it doesn’t display correctly on mobile on my woocommerce product page, https://west-house.co.za/product/peco-powerbrick-package/. See screenshot for clear illustration.
Mobile view
Cannot read properties of undefined (reading ‘forEach’) when no Array
I got this error :
Cannot read properties of undefined (reading ‘forEach’)
if(response.Response) {
$('#list').html('');
response.Search.forEach(function(movie) {
var movieContent;
if(movie.Poster === 'N/A') {
movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year}</li>`;
} else {
movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year} <a href="${movie.Poster}" class="btn btn-xs btn-primary" id="poster-link">Poster</a></li>`;
}
$('#list').append(movieContent).hide().fadeIn();
});
}
});
The error comes when I put less than 3 letters in my search input and the output is
{Response: ‘False’, Error: ‘Too many results.’}
otherwise, from 3 letters the response is correct
{Search: Array(2), totalResults: ‘2’, Response: ‘True’}
I understand that this is because there is no Array in the response but how can I prevent this error?
on function after load jquery
Please tell me, there are 2 pages: index.html
, load.html
.
There is a script that is included in index.html which contains the $('div').on()
function for elements that are on the load.html page.
After calling the $('.el').load('load.html')
function, the events stop working. How beautifully can you make the events fire even after updating the page with elements?
P.S. hanging a function on an element and loading a script in the load.html
page is not suitable, the script is the same on the index.html
page.
How to give TypeORM Datasource from middleware to Nestjs
I have a middleware that create a connection from TypeORM to the database wanted, at each request to the api.
I would like to link the created Datasource connexion to Nestjs and use the Datasource from the Nestjs injections like :
@InjectDatasource()
The only things I could have done was to pass the TypeORM Datasource has a part of request so the controllers could use it.
Is there a way to do it from the Nestjs injection directly ? It would be better and easier for the developpers.
Thanks in advance.
node.js Readable process?
i’m studying node.js stream module
and there’s one problem i can’t solve by myself.
const fs = require('fs')
const {Readable} = require('node:stream')
const rs = new Readable({
read(size) {
if(this.count < 3){
console.log('read: ', this.count)
this.push(`data${this.count + 1}t`)
this.count++
}else{
console.log('read: null')
this.push(null)
}
}
});
const ws = fs.createWriteStream('./big.txt')
rs.count = 0
rs.on('data', (c) => console.log('[data event]'))
rs.pipe(ws);
and big.txt is like this as i expected
data1 data2 data3
but the console.log is like this and this is not what i expected
read: 0
read: 1
[data event]
read: 2
[data event]
read: null
[data event]
i expected this
read: 0
[data event]
read: 1
[data event]
read: 2
[data event]
read: null
why is it different?
can anybody let me know? thanks
Triggering MOUSEDOWN event across all elements within container in JavaScript
I am making a sketchpad (Etch-a-sketch) that colors the blocks within the grid as you click and drag the cursor over them. For that, I used the mousedown event.
The problem I face is that even though I have applied the event to all the elements using a for loop, the mousedown events do not carry over to the other elements within the sketchpad container.
HTML
<body>
<header>
<h1>Sketchpad 1.0</h1>
</header>
<main id="main">
<div class="settings-panel">
<button id="grid-size">CREATE GRID</button>
<button class="hidden" id="pencil">PENCIL</button>
<button class="hidden" id="rainbow">RAINBOW</button>
<button class="hidden" id="eraser">ERASER</button>
<button class="hidden" id="reset">RESET</button>
</div>
<div class="sketchpad">
</div>
</div>
</main>
<footer>
<a href="https://www.linkedin.com/in/guchierrez/" target="_blank">
<img src="./icons/linkedin.png">
</a>
<a href="https://github.com/guchierrez/etch-a-sketch" target="_blank">
<img src="./icons/github.png">
</a>
</footer>
</body>
JavaScript
/*========================================
======5. DRAWING BUTTON FUNCTIONALITY=====
=======PENCIL, RAINBOW AND ERASER=========
========================================*/
pencilButton.addEventListener("click", function () {
const blocks = document.querySelectorAll(".block");
for (i = 0; i < blocks.length; i++) {
const blocks2 = document.getElementById(`block-${i}`);
blocks2.addEventListener("mousedown", function () {
for (i = 0; i < blocks.length; i++) {
blocks2.style.backgroundColor = "black";
}
});
}
});
const colors = [
"#9400D3",
"#4B0082",
"#0000FF",
"#00FF00",
"#FFFF00",
"#FF7F00",
"#FF0000",
];
rainbowButton.addEventListener("click", function () {
const blocks = document.querySelectorAll(".block");
for (i = 0; i < blocks.length; i++) {
const blocks2 = document.getElementById(`block-${i}`);
blocks2.addEventListener("mousedown", function () {
for (i = 0; i < blocks.length; i++) {
let randomColors = colors[(colors.length * Math.random()) | 0];
blocks2.style.backgroundColor = randomColors;
}
});
}
});
eraserButton.addEventListener("click", function () {
const blocks = document.querySelectorAll(".block");
for (i = 0; i < blocks.length; i++) {
const blocks2 = document.getElementById(`block-${i}`);
blocks2.addEventListener("mousedown", function () {
for (i = 0; i < blocks.length; i++) {
blocks2.style.backgroundColor = "white";
}
});
}
});
It works as intended with mouseover, but it colors indefinitely. I would like to be able to color only when the click button is pressed.
Set Button Uppy React File Input as SVG Image
I want to change the button of Uppy File input from string text to svg image, and this is my code :
import { DeleteOutlined } from '@ant-design/icons';
import Uppy from '@uppy/core';
import { FileInput } from '@uppy/react';
function MyComponent() {
const [uppy, setUppy] = useState(null);
function handleMount() {
const uppyInstance = Uppy({
autoProceed: true,
restrictions: {
maxFileSize: 1000000, // example restriction
},
});
setUppy(uppyInstance);
}
function handleUnmount() {
uppy.close(); // close the uppy instance when the component is unmounted
}
const fileInputProps = {
uppy: uppy,
target: '#file-input-container',
pretty: true,
locale: {
strings: {
chooseFiles: 'Choose files'
},
},
};
return (
<div
id="file-input-container"
onMouseEnter={handleMount}
onMouseLeave={handleUnmount}
>
<FileInput {...fileInputProps} />
</div>
);
}
in locale.strings there is string text ‘Choose files’, how to replace to be <DeleteOutlined icon ?
Sharp lines in corners of Threejs BoxGeometry shadows
I made a structure using BoxGeometry, and I have a DirectionalLight rotating around it. The problem is, I can see aliased light bleed in the corners. I’ve tried updating the shadow.mapSize, the blur radius, the renderer.shadowMap.type, but nothing has worked so far.
//left wall
const geometry = new THREE.BoxGeometry( 1, 15, 7 );
const material = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube = new THREE.Mesh( geometry, material );
cube.position.y = 7.5;
cube.position.z = -4.5;
cube.receiveShadow = true
cube.castShadow = true
scene.add( cube );
//right wall
const geometry2 = new THREE.BoxGeometry( 1, 15, 7 );
const material2 = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube2 = new THREE.Mesh( geometry2, material2);
cube2.position.y = 7.5;
cube2.position.z = -4.5;
cube2.position.x = 16;
cube2.receiveShadow = true
cube2.castShadow = true
scene.add( cube2 );
//back wall
const geometry3 = new THREE.BoxGeometry( 1, 15, 15 );
const material3 = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube3 = new THREE.Mesh( geometry3, material3);
cube3.position.y = 7.5;
cube3.position.x = 8;
cube3.position.z = -7.5
cube3.rotateY(Math.PI / 2)
cube3.receiveShadow = true
cube3.castShadow = true
scene.add( cube3 );
//top
const geometry4 = new THREE.BoxGeometry( 1, 7, 17 );
const material4 = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube4 = new THREE.Mesh( geometry4, material4);
cube4.position.y = 15.5;
cube4.position.x = 8;
cube4.position.z = -4.5
cube4.rotateY(Math.PI / 2)
cube4.rotateZ(Math.PI / 2)
cube4.receiveShadow = true
cube4.castShadow = true
scene.add( cube4 );
// DIRECTIONAL LIGHT
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.x += 20
directionalLight.position.y += 20
directionalLight.position.z += 20
directionalLight.castShadow = true
directionalLight.shadow.mapSize.width = settings.shadowMapSize;
directionalLight.shadow.mapSize.height = settings.shadowMapSize;
directionalLight.shadow.radius = settings.shadowRadius
// directionalLight.shadow.blurSamples = 500
const d = 25;
directionalLight.shadow.camera.near = 0.5
directionalLight.shadow.camera.far = 60
directionalLight.shadow.camera.left = - d;
directionalLight.shadow.camera.right = d;
directionalLight.shadow.camera.top = d;
directionalLight.shadow.camera.bottom = - d;
scene.add(directionalLight);
scene.add( new THREE.CameraHelper( directionalLight.shadow.camera ) );
react jest test without assertions to test rendering with getBy queries
@testing-library/react
provides several methods for querying rendered elements including getBy*
queries which will throw an error if the element is not found.
How should I handle this in my test when I just want to test that there rendered elements are on screen.
When the getBy
throws an error if element is not found there is no need to assert that expect(element).toBeInTheDocument()
but then I have a test without assertion.
Should I use a dummy assertion like expect(1).toBe(1)
or whats the best practice here?
Example:
describe("MyComponent", () => {
// Render helper
function renderer(props) {
const result = render(<MyComponent {...props} />);
// Will throw error when element with text "My element" is not found
const element = screen.getByText("My element");
return {...result, element);
}
it("renders with my element", () => {
const {element} = renderer({});
// Redundant, will always pass when reaching this point
expect(element).toBeInTheDocument();
});
// Has same effect but does not use assertion
it("renders with my element w/o assertion", () => {
renderer({});
// expect(1).toBe(1); // When using dummy assertion jest wont complain
});
});
Generic type for key in array.reduce
Have a array of object and by reduce I transform it to {key: [{}], [{}]}, key is date of array
like: [{date: ’22-02-06-00:55:66′, name: ‘one’}…] and result will be {22-02-06: [{}]} all items what includes to this date. My function is:
export function getObjectOfArrayByKey<T, K extends keyof T>(
data: T[],
key: K,
timeFormat: string,
dateFormat: string,
): { [key in keyof T]: T[] } {
return data.reduce((acc, item) => {
const time = dayjs(item[key]).format(timeFormat);
const date = dayjs(item[key]).format(dateFormat);
const equalToDate = {
time,
...item,
};
acc[date] = acc[date] || [];
acc[date].push(equalToDate);
return acc;
}, {} as { [key in keyof T]: T[] & { time: string } });
}
But in constant equalToDate I add new value “time” and I don’t know how add to type script this new type for time.
I think problem is here, I need add new property for type of new array
{ [key in keyof T]: T[] & { time: string }
How can I stop javascript from defining something as true or false before the function is called?
I have some javascript code here for a website (not one I’m gonna publish, I’m just learning) and I’m trying to check if the user input on the page matches a string, but when the if statement executes, it returns “false” rather than “true”, even though if I open my browser’s devtools and print the boolean the same way I get it in the if statement, it returns “true”!
I think it’s defining it as true or false as soon as the page loads.
I’m running the function with an href, and the first thing in the html file’s body is calling the javascript file, but why does it not define it as true or false upon the function being called? How can I fix this issue?
Should I call the script in the href somehow?
Sorry if this is an obvious issue, I’m new to javascript.
I expected it to check the condition when the if statement was executed, but instead it checks the condition as soon as the page opens so theres not even time to type anything.