At present, I use SetSize setposition to change the window size and move the window, but the window always flashes, and the experience is not very good。
Do you have any good solutions?
Category: javascript
Category Added in a WPeMatico Campaign
Deleting item resets progress bar animation?
so I am creating a toast component. I created a progress bar and every time I go to delete a toast item, it resets the progress bar. I had this issue with the whole toast animation and ended up moving it in between a Modal which worked, but im lost as to how to debug the progress bar.
I set animation-fill-mode:forwards but it doesn’t help my issue.
Modal
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './Modal.module.css';
const Modal = ({ children }) => ReactDOM.createPortal(
<>
<div className={styles.modal}>
{children}
</div>
</>, document.getElementById('portal')
);
export default Modal;
Toast
import React, { useState } from 'react';
import { v4 as uuid } from 'uuid';
import Modal from './Modal';
import styles from './Toast.module.css';
/**
* @name Toast
* @return component
*/
const Toast = ({ toasts }) => {
const [toastList, setToastList] = useState(toasts);
const deleteToast = (message) => {
const newList = toastList.filter((toast) => toast.message !== message);
setToastList(newList);
};
return (
<Modal>
{toastList.map((toast) => (
<div key={uuid()} className={styles.toastContainer}>
<div id={styles[toast.type]} className={[styles.toast]}>
<p>{toast.message}</p>
<button
type="button"
className={styles.button}
onClick={() => deleteToast(toast.message)}
>
X
</button>
</div>
<div id={styles[toast.progressType]} className={styles.progress} />
</div>
))}
</Modal>
);
};
export default Toast;
jQuery: How does one bind a field to respond to non-keyboard changes before the field is deselected?
I have a jQuery app with an input text field that has events bound to it such that if the user changes the field then other related fields get updated accordingly. My goal is to make the other fields responsive to every character change. I initially bound the keyup event to the field which works pretty well on a desktop browser:
- If a user pastes to the field via typing Ctrl+V, the other fields are immediately updated via the keyboard events.
- If the user types into the fields, the other correlated fields are immediately updated with each keystroke.
This seemed perfect.
I noticed, however, when testing on a mobile browser, that if the user presses with their finger in the field and selects paste, the keyup event is not triggered. This isn’t surprising since a keyboard isn’t being used on the mobile interface. So I additionally bound change to the field. That worked OK, but the user still has to “deselect” the field after pasting for the change event to be triggered. While playing around with things, I noticed that even on the desktop, if the user pastes to the field with the mouse (right click > paste), then no events are triggered until the field is unselected.
Again, my goal is to make the field more responsive than this for these use cases (mouse paste and mobile paste to the field). Is there a keyboardless event I can bind to that will trigger when the user pastes to the field before deselecting the field?
Thanks.
Why does JSON.stringify(new Error(‘huh’) ) not include the error message field [duplicate]
In NodeJS (same applies to Javascript in browser), why doesn’t JSON.stringify(new Error('huh')) print out the Error.message property?
I was debugging some NodeJS code dealing with a file open error and used JSON.stringify() to the Error object, and was surprised when I didn’t see the message property.
See https://nodejs.org/api/errors.html#class-error for a list of the fields that include:
- error.code
- error.message
- error.stack
To illustrate, copy the following line into your browser console, or run it as a NodeJS file.
console.log(JSON.stringify(new Error('huh')));
// output is: {}
But the field is there as shown by the following lines of code that display the message field.
console.log(JSON.stringify(new Error('huh'))); // {}
console.log((new Error('huh')).toString()); // Error: huh
console.log((new Error('huh')).message); // huh
I’m not sure what to search for to find this answer.
SO had the following but they were unrelated to my question:
For completeness, the MDN (browser) Error object is documented here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
Adding state for each added component
I have a form page. In the example below I have simplified my form. ( Normally the Input below the Textarea is actually a rich editor. )
User can also add text to TextArea using rich editor(Input in Example).
I use the same state for all added components. How can I make this dynamic? I hope my question is clear.
Also, even if I can make a dynamic structure, I have no idea how to make this <p>{csText}</p> dynamic in line 21.
A function declared inside of a function that is in a class cannot access private variables/functions. Is there a way around this?
class a
{
custructor(val)
{
this.val = val;
}
#privFunction()
{
console.log(this.val);
}
publicFunction()
{
var fun = function()
{
this.#privFunction();
};
fun();
}
}
const class1 = new a("Hello world!");
class1.publicFunction();
This will return an error that the this.#privFunction() function is not declared in this scope. If I need to find a way to declare a private function in a function that’s declared inside of a class’ public function is this possible?
Parsing HTML to json object
So I am looking to create a script to return certain values from a JSON. Part of this JSON object I have is HTML. How do I parse the HTML so I can use it in a JSON object?
This is the HTML:
<span style="color:#800000">protected</span></div></div>
<div><div><span style="font-weight:bold;font-size:150%">wummie</span><br /><span style="font-size:105%">Independent Faction</span><br /><span style="font-style:italic;font-size:110%">woman</span><br /><br /><span style="font-weight:bold">SlowlyWastingAway:</span> Deusphage<br /><br /><span style="font-weight:bold">Member Count:</span> 1<br /><span style="font-weight:bold">Age:</span> 2 years, 5 months and 6 days<br /><span style="font-weight:bold">Bank:</span> 0 Regals<br /><br /><span style="font-weight:bold">Flags:</span><br /><span style="color:#800000">open</span> | <span style="color:#800000">monsters</span> | <span style="color:#008000">animals</span><br />
How would I parse it so it is like:
wummie
Independent Faction
woman
SlowlyWastingAway: Deusphage
Member Count: 1
Age: 2 years, 5 months and 6 days
Bank: 0 Regals
Flags:
open | monsters | animals
Passing user input from child functional component to parent functional component
Im creating an invoice generator where the user can add an item, its price, and the quantity. I want to access the user inputs as a state from a child functional component (TableItems.js) into a parent functional component (TableSheet.js) to be able to save the user inputs into a database preferably firestore. I’m having a problem accessing the user input value from the child component to the parent component. I have been struggling with this bug for days, i really hope you guys could help me.
This is the Child component
import React, {useState, useEffect} from 'react'
function TableItems({index, tableItem }) {
const [price, setPrice] = useState(0);
const [qty, setQty] = useState(0);
const [total, setTotal] = useState([]);
useEffect(() => {
//arithmetically add price and qty values
const x = Number(price) * Number(qty)
setTotal(x)
return () => {
//clean up function will be here
};
}, [price, qty, total ]);
return (
<>
<tr>
<td><input type='text' required/></td>
<td><input type='number' value={price} onChange={(e) => setPrice(e.target.value)}/></td>
<td><input type='number' value={qty} onChange={(e) => setQty(e.target.value)}/></td>
<td>{total}</td>
</tr>
</>
)
}
export default TableItems
This is the Parent component
import React, { useState } from 'react'
import TableItems from './TableItems'
function TableSheet() {
const [tableItem, setTableItem] = useState([1]);
//adding a new table cell (table row)
const addCell = () => {
setTableItem((t) => [...t, t + 1])
}
return (
<div>
<table>
<thead>
<th>Item Description</th>
<th>Price</th>
<th>Qty.</th>
<th>Total</th>
</thead>
{
tableItem.map((tableItem, index, setItem) => {
return <TableItems key={index} tableItem={tableItem} setItem={setItem} addCell={addCell}/>
})
}
</table>
<button onClick={addCell}>+</button>
</div>
)
}
export default TableSheet
Can you use the Array.prototype.find() to check against more than one condition to find something?
I am creating a calculator app in JS and I got it to work by using the mouse to click buttons on the screen so I am now integrating the use of the keyboard. Long story short, in part of my functionality before the keyboard was being used I was using the find property on an array to find the last operator clicked that was NOT the = btn and it worked perfectly fine:
lastOperatorThatIsNotEqual = operatorArray.reverse().find(e => e !== "=")
Now that I am using the keyboard, when I click enter I want it to be the equivalent of clicking the = btn so I tried doing it this way using an external function and an if/else statement
function test(e) {
if (e !== 'Enter') {
return e
} else if (e !== '=') {
return e
} else {
console.log('wrong')
}
}
lastOperatorThatIsNotEqual = operatorArray.reverse().find(test)
However the above does not work. If I remove the else if portion so it’s just e !== 'Enter' or e !== '=' then it works fine but I can’t have both in there at the same time. I figure it’s probably more efficient to have it check that way instead of doing two functions but can’t figure out why this isn’t working.
Any suggestions are much appreciated. Thanks!
Test if a function is called after a promise in React
I’m learning to test React applications, right now I have a function that will run after a promise (innerFunction) in my App.jsx, like this:
function App() {
const [isReady, setIsReady] = useState(false);
const innerFunction = wrapperFunction();
useEffect(() => {
thirdPartyPkg.onReady().then(() => innerFunction(isReady, setIsReady));
}, []);
// ...
}
This is what the code on wrapperFunction.js looks like:
export function wrapperFunction() {
return function innerFunction(isReady, setIsReady) {
if (isReady) {
setIsReady(true);
}
};
}
And this is my App.test.jsx:
import * as Function from "./utils/wrapperFunction";
describe("testing App", () => {
it("should run innerFunction once after promise", () => {
const inner = jest.spyOn(Function, "wrapperFunction");
expect(inner).toBeCalledTimes(1);
});
});
I’m guessing that I need to wait to the promise to resolve, but I’m kind of blocked, do you guys have any suggestion to test if the innerFunction is called?
How to assign values from an object to properties in an array, conditionally
I need to assign values from an array of objects, to an object, with different keys.
In the JavaScript app, I’m working with, I get an array of objects returned similar to below:
urlArrayOfObjects = [
{url: 'https://amazon.co.uk', country: 'uk'},
{url: 'https://amazon.com', country: 'usa'},
{url: 'https://amazon.ca', country: 'canada'},
{url: 'https://amazon.es', country: 'spain'}
]
The object is the something like the following:
urlTables = {
short_url_id: "",
uk_url: "",
usa_url: "",
canada_url: "",
irland_url: "",
spain_url: "",
germany_url: "",
default_country: "",
default_url: "",
customer_id: ""
}
I need to extract values from urlArrayOfObjects and insert them into the appropriate properties in the urlTables (And if there are no values, if should default to null
For e.g. in the above case, urlTables should look like the following after I’m done with it:
urlTables = {
short_url_id: null,
uk_url: "https://amazon.co.uk",
usa_url: "https://amazon.com",
canada_url: "https://amazon.ca",
irland_url: null,
spain_url: "https://amazon.es",
germany_url: null,
default_country: null,
default_url: null,
customer_id: null}
What is the best way of going about achieving this?
Thank you so much for your help!
Array.Filter() using a callback function to compare two arrays
Insted of doing using an anonymous function how
const ArrayOverlap = (arr1, arr2) =>{
let newArr = [];
return newArr = arr1.filter(element => arr2.includes(element));
}
If I was to do something like
const ArrayOverlap = (arr1, arr2) =>{
let newArr = [];
return newArr = arr1.filter(bothIncluded(arr1, arr2));
}
function bothIncluded(arr1, arr2){
for(const item of arr1){
return arr2.includes(item);
}
Javascript for in loop and pop() [duplicate]
I just learnt the arrays for-of loop which iterates through each elements of an array and I used it to empty an array using pop() which removes the last element of an array but this isn’t working.
let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of skills) {
skills.pop();
}
console.log(skills); // HTML , CSS, Javascript
How add custom image to textballoon Leaflet
I want to add a custom textballoon/popup to my leaflet map.
I totally stuck atm.
The popup i add as new layer because for automatic open on load.
My code:
const map = L.map('map').setView([52.2129919, 5.2793703], 8);
// load a tile layer
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a>',
maxZoom: 18,
}).addTo(map);
let markersArray = {}; // create the associative array
let magsArray = {}; // here hold the ids that correspond to the mags
// load GeoJSON from an external file
$.getJSON("geojs.php", data => {
L.geoJson(data, {
// add GeoJSON layer to the map once the file is loaded
pointToLayer: function(feature, latlng) {
const mag = feature.properties.message;
// here record the mags
magsArray[feature.properties.id] = feature.properties.place+' '+feature.properties.message;
//testpopup
var popupLocation1 = (feature, latlng);
<!-- var popupContent1 = '<span class="speed speed-current leaflet-zoom-hide speed-confirmed"><span class="speedContent"><span class="dateTxt">'+feature.properties.place+'</span><br><span class="speedTxt">'+feature.properties.message+'</span><span class="kmphTxt">km/h</span>'+'</span></span>', -->
var popupContent1 = '<span class="speedContent"><span class="dateTxt">'+feature.properties.place+'</span> <span class="speedTxt">'+feature.properties.message+'</span><span class="kmphTxt">km/h</span></span>',
popup1 = new L.Popup();
popup1.setLatLng(popupLocation1);
popup1.setContent(popupContent1);
map.addLayer(popup1);
},
});
});
How it now looks:
How i want it:
The logo:
I hope some one can help me,
Kind regards.
What rendering method should I use in my next Js app?
I’m building a next Js web app, I know all the basics about rendering, SSR, SSG etc. But still asking here cause I have some doubts.
In the app, users will be able to post content, content includes files, images too and other user will be able to see that content. Like social media, not exactly like social media. I was thinking about implementing SSR cause then the search engine bots will be able to list that posts on Google. but from my experience I have seen Server side rendering being slow, especially when there is a ton of content to load, client side rendering is not a godman either it can be slow too but at least I can make user wait by loaders. In SSR, a non loading blank page for even 2 seconds is a huge L.
So back to my question what should I use. I’m in confusion.
One more question if anyone knows: do companies like Instagram, udemy, upwowk use server side rendering when showing posts?


