2 elements rotating but they are changing speed while it should be constant

7s / 11s mark (4x Speed up)

So the red one is children of the blue one, when the blue one rotates, the red one too. But, the red one also have its own rotating speed. The problem is that the red one’s speed isn’t constant, probably because I am using 2 setInterval functions that are responsible for both rotating’s time… So, for example, each 2 seconds the blue moves 10 px and each 1 second the red moves 5px. Every odd second, red moves 5px. Every even second, red moves 15px. How can I keep it the same?

<!DOCTYPE html>

<html lang="en-US">
    <head>
        <link href="test.css" rel="stylesheet">        
        <title>Orbit</title>
    </head>

    <body>
        <div class="box">
            <div id="earth">            
                <div id="moon"></div>
            </div>
            
        </div>      
        
        <script>

            r_moon = 100; // radius
            r_earth = 200;
            a = 0;
            b = 0;

            function rotate_moon(a)
            {            
                var px_moon = r_moon * Math.cos(a);
                var py_moon = r_moon * Math.sin(a);
                
                document.querySelector('#moon').style.left = px_moon + "px";
                document.querySelector('#moon').style.top = py_moon + "px";
            }

            function rotate_earth(b)
            {            
                var px_earth = r_earth * Math.cos(b);
                var py_earth = r_earth * Math.sin(b);
                
                document.querySelector('#earth').style.left = px_earth + "px";
                document.querySelector('#earth').style.top = py_earth + "px";
            }


            setInterval(function moon()
            {
                a = (a + Math.PI / 360) % (Math.PI * 2);
                rotate_moon(a);
            }, 10);

            setInterval(function earth()
            {
                b = (b + Math.PI / 360) % (Math.PI * 2);
                rotate_earth(b);
            }, 50);
            
        </script>

    </body>

</html>
html
{
    height: 100%; width: 100%;
}

body
{
    margin: 0;
}

.box
{
    margin: auto; margin-top: 200px;
    height: 400px;
    aspect-ratio: 1 / 1;
    display: flex; justify-content: center; align-items: center;
}

#earth
{
    position: relative;
    height: 30px;
    aspect-ratio: 1 / 1;
    display: flex; justify-content: center; align-items: center;
    background-color: blue;
}

#moon
{
    position: relative;
    height: 20px;
    aspect-ratio: 1 / 1;
    background-color: red;
}

Vue.js change class on mounted

I have a button element with a .hover property and I need the hover animation to also happen as soon as the page is mounted. How can I attribute a class to a button on the mounted function and then disattribute it?

I was thinking of using a setTimeout but it’s not working properly. I’m basing my code off of this codePen: https://codepen.io/lucasfads/pen/QWwjGjv

<a href="#" class="button" id="specialButton">
  <span class="icon"></span>
  <span class="text">Hakuna Matata</span>
</a>
mounted() {
  document.getElementById("specialButton").classList.add("expanded");

  setTimeout(() => {
    document.getElementById("specialButton").classList.remove("expanded");
  }, 3000);
}
.button {
  background-color: #099;
  color: white;
  text-decoration: none;
  border-radius: 60px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  overflow:hidden;
  width: auto;
  max-width: 32px;
  transition: max-width 0.5s;
}

.button:hover,
.button .expanded {
  max-width: 300px;
}

.icon {
  font-family: "Font Awesome 5 Free";
  font-size: 16px;
  margin-right: 15px;
  padding: 0px 8px;
  display: flex;
  align-items: center;
}

.text {
  white-space: nowrap;
  padding-right: 15px;
}

RepaidAPI Proplem

When I try to sync my RapidAPI projects in vs code I get an error telling me “Failed to retrieve projects”

I tried to uninstall the RapidAPI extension and install it again and tried to sign in with a different account but nothing happened

Trying to programmatically click a Load More button on https://www.publix.com/savings/digital-coupons but .click() does nothing

I’m on the Publix coupon site: https://www.publix.com/savings/digital-coupons and trying to click the Load More button from within the Console in Dev Tools.

when I inspect the “Load More” button it points me to a button but .click() does not seem to have the intended effect.

Inspecting the button gives me

<button data-v-2950ea31="" type="submit" class="p-button button--default button--sm button--secondary"><!----> <span data-v-0eea259a="" data-v-2950ea31="" class="button__label p-text paragraph-sm strong context--default color--null">
        Load more
    </span></button>

I can then select the button with:

tmpqs = document.querySelector('button[class="p-button button--default button--sm button--secondary"]');

but when I do tmpqs.click() nothing happens. I added an onclick alert and the click is registering but the site is not loading more things. Other sites seem to work with this workflow no problem.

I tried setting Event Listener Breakpoints for Mouse clicks to follow what’s happening but can’t seem to figure it out. Also using Tab to tab to the element and then hitting space results in loading more items.

Any ideas or pointers would be appreciated.

What is new Errormessage

facing this error like for some time now but fixed it from a link in git
https://github.com/evanw/esbuild/issues/1642
here is my error snippet from the terminal

npm ERR! code 1
npm ERR! path /home/trie/urban_sniffle/node_modules/esbuild
npm ERR! command failed
npm ERR! command sh -c -- node install.js
npm ERR! node:internal/errors:857
npm ERR!   const err = new Error(message);
npm ERR!               ^
npm ERR! 
npm ERR!     /home/trie/.npm/_logs/2023-06-04T00_28_13_111Z-debug-0.log

Lazy load images on a screen containing multiple horizontal scroll sections, when they’re close to the bottom or right of the viewport

Goal: I would like for my images to load once they’re within a certain percent or number of pixels (happens to be 20% in my example) of the right or bottom of the viewport

I tried 2 approaches. I made comments on my approaches in the code and you can easily toggle each approach on and off. With one approach, the right margin behaves correctly and the bottom margin doesn’t. And with the other approach, the opposite happens: the right margin doesn’t work correctly, but the bottom margin does.

JavaScript:

import React, {useEffect} from 'react';
import './test.css';

// dummy test data
const coffeeShops = [
    {
        title: 'Coffee Shop 1',
        photos: [
            'picture 1 of Coffee Shop 1',
            'picture 2 of Coffee Shop 1',
            'picture 3 of Coffee Shop 1',
            'picture 4 of Coffee Shop 1'
        ]
    },
    {
        title: 'Coffee Shop 2',
        photos: [
            'picture 1 of Coffee Shop 2',
            'picture 2 of Coffee Shop 2',
            'picture 3 of Coffee Shop 2',
            'picture 4 of Coffee Shop 2'
        ]
    },
    {
        title: 'Coffee Shop 3',
        photos: [
            'picture 1 of Coffee Shop 3',
            'picture 2 of Coffee Shop 3',
            'picture 3 of Coffee Shop 3',
            'picture 4 of Coffee Shop 3'
        ]
    },
    {
        title: 'Coffee Shop 4',
        photos: [
            'picture 1 of Coffee Shop 4',
            'picture 2 of Coffee Shop 4',
            'picture 3 of Coffee Shop 4',
            'picture 4 of Coffee Shop 4'
        ]
    }
]

export const Test = () => {
    useEffect(() => {
        const svgs = document.querySelectorAll('.mySvg');
        // I am setting the images to load once they come within 20% of the right or bottom of the viewport.
        const rootMargin = '0% 20% 20% 0%';

        // Approach 1:
        // bottom viewport works!
        // right viewport doesn't work: The images load right when they intersect with the right side of the viewport (i.e. 0% instead of the 20% that I set) :(
        createObserver(svgs, rootMargin, null);

        // Approach 2: (the exact opposite happens)
        // bottom viewport doesn't work: If you scroll down you can see that all the images already loaded when the page loaded :(
        // right viewport works!
        // const scrollContainers = document.querySelectorAll('.scroll-container');
        // for (const scrollContainer of scrollContainers) {
        //     createObserver(svgs, rootMargin, scrollContainer);
        // }
    }, [])

    return (
        <>
            <div style={{marginBottom: '50px'}}>Awesome Coffee Shops:</div>

            {coffeeShops.map(shop => {
                return (
                    <>
                        <div className='scroll-container'>
                            {shop.photos.map(photo => {
                                return (
                                    <svg width='4032' height='3024' class='mySvg'>
                                        <rect x="0" y="0" width='4032' height="3024" stroke='black' fill='white' />
                                    </svg>

                                );
                            })}
                        </div>
                        <div>{shop.title}</div>
                    </>
                );
            })}
        </>
    );
};


export const createObserver = (svgs, rootMargin, root) => {
    const config = {
        root,
        rootMargin,
        threshold: 0
    };

    const lazyImageObserver = new IntersectionObserver(function (entries, observer) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
                const svg = entry.target;
                setTimeout(() => svg.childNodes[0].setAttribute('fill', 'purple'), 500); // the setTimeout simulates downloading an image
                observer.unobserve(svg);
            }
        });
    }, config);

    svgs.forEach(function (svg) {
        lazyImageObserver.observe(svg);
    });
};

css

.scroll-container {
    overflow: auto;
    white-space: nowrap;
}

Does TypeScript checking on VSCode not detect await functions?

I am writing an app which obtains weather data about a user’s location, and so far, everything works. However, when writing the code, I keep getting errors being highlighted, even though the code works.

Here is the code:

function array_to_comma_sep(array: Array<string>) {
    let output: string = String();
    for (let ele of array) {
        output += ele + ",";
    }
    return output.substring(0, output.length-1);
}

class Feature {
    name: string;
    unit: string;
    constructor(name: string, unit: string) {
        this.name = name;
        this.unit = unit;
    }
}

type GeoLocation = {
    latitude: number;
    longitude: number;
}

async function getWeatherData() {

    const HOURLY_FEATURES: Array<Feature> = [
        new Feature("temperature_2m", "celsius"),
        new Feature("relativehumidity_2m", "%"),
        new Feature("apparent_temperature", "celsius"),
        new Feature("precipitation_probability", "%"),
        new Feature("precipitation", "mm"),
        new Feature("snow_depth", "m"),
        new Feature("visibility", "m")
    ]

    // gets user's ip address
    let ip_address: string;
    await $.getJSON("https://api.ipify.org?format=json", data => {
        ip_address = data.ip;
    });
    
    // get user's location
    let location: GeoLocation;
    await $.get(`https://ipapi.co/${ip_address}/latlong/`, data => {
        let [lat, long]: Array<number> = data.split(",").map((num: string) => { return parseFloat(num); });
        location = {
            latitude: lat,
            longitude: long
        }
    });

    // get information about the weather
    let hourly_features = array_to_comma_sep(HOURLY_FEATURES.map((feat: Feature) => { return feat.name }));
    await $.getJSON(`https://api.open-meteo.com/v1/forecast?latitude=${location.latitude}&longitude=${location.longitude}&hourly=${hourly_features}`, data => {
        console.log(data);
    })

}

getWeatherData();

The problematic parts arise due to VS Code’s syntax highlighting – it says that, in the line with await $.getJSON("https://api.ipify.org?format=json", data => {, I am the “Variable ‘ip_address’ is used before being assigned. ts(2454)`.

However, as aforementioned, in terms of performance, everything goes well. I can see my API response in the console as expected.

Does the TypeScript extension I have not realize that the value will be assigned later as the function is async, or am I doing something wrong? This is my first time using TypeScript.

Here is my HTML code as well.

<!DOCTYPE html>
<head>  
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="app.tsx" type="text/babel"></script>
</head>
<body>
    <div id="container"></div>
</body>

Importxml from site using javascript

I am getting #N/A while retrieving price data from https://www.daraz.com.bd/.

My formula is =IMPORTXML(“https://www.daraz.com.bd/products/tresemme-shampoo-botanique-nourish-and-replenish-580ml-i2456416.html”,”/html/body/div[4]/div/div[3]/div[2]/div/div[1]/div[7]/div/div/span”)
Kindly tell me the correct formula for price from importxml.
i want to get the listing price of different products on amazon and daraz. Other web scraping tool are paid and this formula is not working.
Kindly help/.

jQuery error [intervention] Ignored attempt to cancel a touchend event with

I working with jQuery UI and jquery.ui.touch-punch, When resizing the object, it gives me the following error:

*Note: The error appears when I test in chrome (PC) in mobile mode (Ctrl+Shift+M)

[Intervention] Ignored attempt to cancel a touchend event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.

Screenshot:

enter image description here

I don’t understand what the error is, how do I fix it?

I have no experience with this error, where is the error?

Chat client implementing my own transfer protocol

I’m looking to build my own real time chat client and server but would like to do so without existing libraries like websockets or socket.io. Ideally I would like to be able to build my own network protocol, something like my own version of the web socket protocol with the default functionality provided by JavaScript and node.js. Does anybody have any guidance as to where to start or what options I have? Thanks in advance.

How do I change css class of html paragraph with javascript?

So the way I want to do the toggling of light and dark themes is that every thing that changes will have an other class in css that it will change to.

Like this:

css:

.p-fooldal
{
    color:black;
}

.p-fooldal-light-mode
{
    color:white;
}

html:

<p class="p-fooldal"> asd asd </p>

JS is where I need help. I have done the some with the body, but I cant do the same, because I want different style for different paragraphs, what other way can I refer to a paragraph.

var body = document.body;

function toggleDark()
{
    body.classList.toggle("body-light-mode");
}

I have tried bruteforcing myself whit this:

const pfooldal = document.classList.pfooldal;

function toggleDark()
{
    pfooldal.classList.toggle("p-fooldal-light-mode")
}

I know its awful but it has to be something like that.

Naming function parameters when comparing whether test value is smaller or higher than target value [closed]

I have a function that compares if one date is before another date.

function isBefore(testDate: Date, targetDate: Date): boolean {
    return testDate < targetDate;
}

Probably there will be biased opinions, but is there any practice which parameter goes first and which goes second in function definition?

const day1 = new Date('2023-06-03');
const day2 = new Date('2023-06-02');

isBefore(day1, day2); // false
isBefore(day2, day1); // true

Probably documenting function will make it easier to understand and there is good practice with comparators in general, that if first argument goes before second, function returns -1, if equal 0, if greater 1, but this applies for comparators in sorting and not in boolean returning functions.

This example not worth creating helper function as you can compare dates in place, but a question is in general for any values to be tested. You can imagine something with more complex algorithm (like comparing importance of two tasks).

How can I persuade myself to learn TypeScript? [closed]

I’ve been searching for the benefits of TypeScript approximately 5 days, but i do not have find any benefit to persuade myself to learn TypeScript. In programming, The important is performance and minimum code for me. Other than that, To define type for everything takes longer time. So, I realised the code that i write in JavaScript takes longer time in TypeScript. I do not think that defining types is so important that much. Some websites says TypeScript is OOP but JavaScript does not.Lol. I think their posts behind the era. TypeScript has a bigger circle that JavaScript’s, but i do not have realised what is the rest outside of JavaScript yet. I watched some videos where TypeScript was used together with React, and i saw that the all of the code looked like the text which I am writing right now. It was really horrifying. Long story short, why should i learn TypeScript while everything is possible through JavaScript and React?

7 reasons describing why It is unnecessary

Issue with changeHandler, component re renders every time i do some change

My plan is to make stepper component in modal so the every step will have own component.So i use switch case logic and that works fine for me it return the step and step component properly. I have issue on change handler, when i start to type it seems that my component re renders every time i do some change. Here is a parent Modal component

export function ContactModal(props) {
    const [step, setStep] = useState(0)
    let stepArray = [1, 2, 3, 4, 5, 6]


    const handleNextStep = () => {
        const nextStep = step + 1;
        if (step === 1) {
            let checked = document.querySelectorAll('input[type=checkbox]:checked').length
            if (!checked) {
                alert("You must check at least one checkbox.")
            } else {
                setStep(nextStep)
            }
        } else {
            setStep(nextStep)
        }
    }
    const handleBackStep = () => {
        const back = step - 1;
        setStep(back)
    }
    const inputHandler = (event) => {
        event.preventDefault()
        props.setData((prevState) => ({
            ...prevState,
            [event.target.name]: event.target.value,
        }));
    };

    const checkboxHandler = (event) => {

        let savedData;
        savedData = {
            ...props.data,
            [event.target.name]: event.target.checked,
        };
        props.setData(savedData)

    };

    const handleChangeTimepicker = (newValue, name) => {
        props.setData({...props.data, [name]: new Date(newValue)});
    };

    let CurrentStep;

    switch (step) {
        case 0:
            CurrentStep = () => (
                <RequestProject nextStep={handleNextStep} onHide={props.onHide} step={step} setStep={setStep} />
            );
            break;
        case 1:
            CurrentStep = () => (
                <Step1 checkboxHandler={checkboxHandler} nextStep={handleNextStep} data={props.data} />
            );
            break;
        case 2:
            CurrentStep = () => (
                <Step2 handleChangeTimepicker={handleChangeTimepicker} data={props.data} nextStep={handleNextStep} />
            );
            break;
        case 3:
            CurrentStep = () => (
                <Step3 checkboxHandler={checkboxHandler} nextStep={handleNextStep} data={props.data} />
            );
            break;
        case 4:
            CurrentStep = () => (
                <Step4 inputHandler={inputHandler} nextStep={handleNextStep} data={props.data} setData={props.setData} />
            );
            break;
        default:
            CurrentStep = null;
    }


    return (
        <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered>
            {step > 0 && (
                <Modal.Header className="d-flex justify-content-between align-items-center border-bt-none w-100  px-5">
                    <p onClick={handleBackStep} className="text-md m-0 cursor-pointer text-primary">
                        <IoIosArrowBack />Back
                    </p>
                    <StepperDots stepArray={stepArray} step={step} />
                    <p onClick={props.onHide} className="text-md m-0 cursor-pointer text-primary">
                        Close
                    </p>
                </Modal.Header>
            )}
            <Modal.Body>
                {CurrentStep && <CurrentStep />}
            </Modal.Body>
        </Modal>

    )
}

and here is my child compoenet :

export function Step4({nextStep, data, setData}) {

    const changeHandler = useCallback((event) => {
        const {name, value} = event.target;
        setData((prevState) => ({
            ...prevState,
            [name]: value,
        }));
    }, [setData]);

    return (
        <>
            <div className="d-flex flex-column align-items-center justify-content-center h-100">
                <h4 className="mb-3 w-50 text-center">About your company</h4>
                <Form className="my-5">
                    <Form.Group className="mb-3">
                        <Form.Label>Your Name <span className="text-gray">(optional)</span></Form.Label>
                        <Form.Control onChange={changeHandler} type="text" value={data.name} name="name"/>
                    </Form.Group>
                    <Form.Group className="mb-3">
                        <Form.Label>Your Company Name <span className="text-gray">(optional)</span></Form.Label>
                        <Form.Control onChange={changeHandler} type="text" value={data.companyName} name="companyName"/>
                    </Form.Group>
                    <Form.Group className="mb-3">
                        <Form.Label>Your Website/Instagram </Form.Label>
                        <Form.Control onChange={changeHandler} type="text" value={data.website} name="website"/>
                    </Form.Group>
                </Form>

                <button onClick={nextStep} className="btn text-white mt-5">Next</button>
            </div>
        </>
    );
}

i try also to set my state upper level and pass that as prop, but still same issue.