useRef not working as expected in child component

I have a component that handles user authentication and displays a login form if needed, otherwise just displays the children.

function AuthWrapper({children}){
  let [auth, setAuth] = React.useState(null);
  React.useEffect(()=>{
    // Do stuff to check or change state
  }, []);
  let component = (<>Loading...</>);
  if(auth){
    component = (<>{children}</>);
  }
  return component;
}

Then I use it in another component where I need to access stuff in the DOM with a ref.

function App(props) {
  let inputRef = React.useRef();
  React.useEffect(()=>{
    console.log('currentRef', inputRef.current);
  }, []);
  return (
    <AuthWrapper>
      <input placeholder='Enter your name' ref={inputRef} />
    </AuthWrapper>
  );
}

Problem is, obviously, there’s nothing in the DOM to reference at the time the useEffect is called because the AuthWrapper hasn’t rendered the children yet. Therefore, inputRef.current is always undefined.

I kind of understand the problem, but every solution I’ve tried has either failed or just felt really gross and hacky. What are some best practices or clean solutions for setting my reference to a DOM element that doesn’t render immediately, and then accessing it once it does render?

Here’s an online code playground demo: https://playcode.io/1769946

Can I render font onto an HTML canvas at a large size, and then downsample it to fit the canvas?

I have a small canvas:

<canvas id="game-canvas" width="256" height="232"></canvas>

I’m scaling it to fit the window with:

html,
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
  image-rendering: pixelated;
  background: black;
}

canvas {
  background: black;
  width: 100vh;
  margin: auto;
  display: block;
}

This is how I’m drawing the text on the canvas, using an external font.

const canvas = document.querySelector('#game-canvas');
const ctx = canvas.getContext('2d');

---

const draw = () =>
{
    // draw objects in mounted scene
    mainScene.draw(ctx, 0, 0);

    var numRupees = 0;
    var numKeys = 0;
    var numBombs = 0;

    // text 
    ctx.fillText('X' + numRupees, gridCells(13), gridCells(2.75));
    ctx.fillText('X' + numKeys, gridCells(13), gridCells(4.75));
    ctx.fillText('X' + numBombs, gridCells(13), gridCells(5.75));
    ctx.fillText("It's dangerous to go", canvas.width / 2, canvas.height / 2 - 15);
    ctx.fillText("alone! Take this.", canvas.width / 2, canvas.height / 2 - 7.5);
};

---

const tlozFont = new FontFace('tloz', 'url(./public/fonts/the-legend-of-zelda-nes.ttf)');

tlozFont.load().then(function (font) {
    document.fonts.add(font);
    document.body.classList.add('fonts-loaded');
    console.log('Font loaded.');

    ctx.font = '8px tloz';
    ctx.textAlign = 'center';
    ctx.fillStyle = 'white';
});

The problem is that my canvas is rendering clearly, but the text is pixelated – because I have to use a font size of 8px to size it properly. I noticed that when I set the font size to something crazy like 1000px, it’s clear – but obviously way too big to fit the canvas.

My canvas:

My canvas.

Is it possible to render the font at that larger size, and then just scale it down to fit the canvas?

I’ve spent days trying out every single solution I find on google, but nothing works. Either they make the canvas and font too small, or they make the font clear but the canvas blurry.

Sort and Count the array and create two property then display result on every first data

I have this sample data.

let data = [
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 1, GroupCode: 'B'},
    {BatchNumber: 1, GroupCode: 'C'},
    {BatchNumber: 1, GroupCode: 'B'},
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 2, GroupCode: 'C'},
    {BatchNumber: 2, GroupCode: 'B'},
    {BatchNumber: 2, GroupCode: 'A'},
    {BatchNumber: 2, GroupCode: 'C'}
];

I want to create a two property in this data named countBatch and countGroup.

First, I need to sort data to show them in ascending order and group each data of GroupNumber, so I create this method:

data.sort((a, b) => {
    if (a.BatchNumber === b.BatchNumber) {
        return a.GroupCode.localeCompare(b.GroupCode);
    }
    return a.BatchNumber - b.BatchNumber;
});
const sortedGroup = {};
data.forEach((item) => {
    const key = `${item.BatchNumber}-${item.GroupCode}`;
    if (!sortedGroup[key]) {
        sortedGroup[key] = [];
    }
    sortedGroup[key].push(item);
});

Now, I will add property in the data named countGroup, and then show only the counted value in the first data of array each from GroupCode, the rest should be in null value. For example;

{BatchNumber: 1, GroupCode: 'A', countGroup: 3},
{BatchNumber: 1, GroupCode: 'A', countGroup: null},
{BatchNumber: 1, GroupCode: 'A', countGroup: null},
{BatchNumber: 1, GroupCode: 'B', countGroup: 2},
{BatchNumber: 1, GroupCode: 'B', countGroup: null},
{BatchNumber: 1, GroupCode: 'C', countGroup: 1},
{BatchNumber: 2, GroupCode: 'A', countGroup: 1},
{BatchNumber: 2, GroupCode: 'B', countGroup: 1},
{BatchNumber: 2, GroupCode: 'C', countGroup: 2},
{BatchNumber: 2, GroupCode: 'C', countGroup: null}

For the above result I create another method: I iterate over the index of sortedGroup so I use Object.keys() function and then I will make a condition that if index is equal to 0, it add value on the property(countGroup). Else, make the value to null.
Here’s the method I created:

var result = [];
Object.keys(sortedGroup).forEach((key) => {
    const group = sortedGroup[key];
    group.forEach((data, index) => {
        if (index === 0) {
            data.countGroup = group.length;
        } else {
            data.countGroup = null;
        }
        result.push(data);
    });
});

Doing the above code, I can now get the result I want.
Here’s a demo.

let data = [
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 1, GroupCode: 'B'},
    {BatchNumber: 1, GroupCode: 'C'},
    {BatchNumber: 1, GroupCode: 'B'},
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 2, GroupCode: 'C'},
    {BatchNumber: 2, GroupCode: 'B'},
    {BatchNumber: 2, GroupCode: 'A'},
    {BatchNumber: 2, GroupCode: 'C'}
];
data.sort((a, b) => {
    if (a.BatchNumber === b.BatchNumber) {
        return a.GroupCode.localeCompare(b.GroupCode);
    }
    return a.BatchNumber - b.BatchNumber;
});
const sortedGroup = {};
data.forEach((item) => {
    const key = `${item.BatchNumber}-${item.GroupCode}`;
    if (!sortedGroup[key]) {
        sortedGroup[key] = [];
    }
    sortedGroup[key].push(item);
});
var result = [];
Object.keys(sortedGroup).forEach((key) => {
    const group = sortedGroup[key];
    group.forEach((data, index) => {
        if (index === 0) {
            data.countGroup = group.length;
        } else {
            data.countGroup = null;
        }
        result.push(data);
    });
});
console.log(result);

Lastly, I will add the property named countBatch in the data. Since the value will count the Batch, I create a variable and a method that count the batch: Here’s the method I used:

const batchCounts = {};
data.forEach((item) => {
    if (!batchCounts[item.BatchNumber]) {
        batchCounts[item.BatchNumber] = 0;
    }
    batchCounts[item.BatchNumber]++;
});

And then, add the result of batchCounts inside the iteration of sortedGroup. I add variable called batchCount with value of batchCounts[group[0].BatchNumber]. This shows the count value of BatchNunber and just pass it to iterattion of group by doing data.countBatch = batchCount;

The PROBLEM is; the value of countBatch is inserted everytime the countGroup value is inserted. I want only to insert the value of countBatch in the first data of each batch number.

CURRENT

let data = [
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 1, GroupCode: 'B'},
    {BatchNumber: 1, GroupCode: 'C'},
    {BatchNumber: 1, GroupCode: 'B'},
    {BatchNumber: 1, GroupCode: 'A'},
    {BatchNumber: 2, GroupCode: 'C'},
    {BatchNumber: 2, GroupCode: 'B'},
    {BatchNumber: 2, GroupCode: 'A'},
    {BatchNumber: 2, GroupCode: 'C'}
];


data.sort((a, b) => {
    if (a.BatchNumber === b.BatchNumber) {
        return a.GroupCode.localeCompare(b.GroupCode);
    }
    return a.BatchNumber - b.BatchNumber;
});
const sortedGroup = {};
data.forEach((item) => {
    const key = `${item.BatchNumber}-${item.GroupCode}`;
    if (!sortedGroup[key]) {
        sortedGroup[key] = [];
    }
    sortedGroup[key].push(item);
});
const batchCounts = {};
data.forEach((item) => {
    if (!batchCounts[item.BatchNumber]) {
        batchCounts[item.BatchNumber] = 0;
    }
    batchCounts[item.BatchNumber]++;
});
var result = [];
Object.keys(sortedGroup).forEach((key) => {
    const group = sortedGroup[key];
    const batchCount = batchCounts[group[0].BatchNumber];
    group.forEach((data, index) => {
        if (index === 0) {
            data.countBatch = batchCount;
            data.countGroup = group.length;
        } else {
            data.countBatch = null;
            data.countGroup = null;
        }
        result.push(data);
    });
});
console.log(result);

EXPECTED

let expected = [
    {BatchNumber: 1, GroupCode: 'A', countBatch: 6,countGroup: 3},
    {BatchNumber: 1, GroupCode: 'A', countBatch: null,countGroup: null},
    {BatchNumber: 1, GroupCode: 'A', countBatch: null,countGroup: null},
    {BatchNumber: 1, GroupCode: 'B', countBatch: null,countGroup: 2},
    {BatchNumber: 1, GroupCode: 'B', countBatch: null,countGroup: null},
    {BatchNumber: 1, GroupCode: 'C', countBatch: null,countGroup: 1},
    {BatchNumber: 2, GroupCode: 'A', countBatch: 4,countGroup: 1},
    {BatchNumber: 2, GroupCode: 'B', countBatch: null,countGroup: 1},
    {BatchNumber: 2, GroupCode: 'C', countBatch: null,countGroup: 2},
    {BatchNumber: 2, GroupCode: 'C', countBatch: null,countGroup:  null}
];
console.log(expected);

Getting data from the .next() function using axios [duplicate]

Below are two custom functions I’ve created. One of them uses the axios package. Everything works correctly except for how to ensure that the “then()” statement in the getData function adds the results to the getResults variable from the r variable.

Could someone explain to me is this possible at all?

import axios from 'axios';

const getDataCount = () => {

    /**
     * Endpoint url
     */
    const DATA_COUNT_URL = '<redacted>';

    /**
     * Makes request to the endpoint.
     */
    const getData = async (url) => {
        try{
            const response = await axios.get(url);
            console.log(response.data)
            return response.data;

        }catch(err){
            console.error(err);
            process.exitCode = 1;
        }
    }   
    return getData(DATA_COUNT_URL);
};

export default getDataCount;

How can I get the “then()” function to add r to getResults of the getData function?

import getDataCount from "./data/getDataCount";

const getData = (key, initialValue) => {

    const getResult = [];
    
    // How can I get the "then()" function to add r to getResults
    getDataCount().then(r => console.log(r))

    // process result
    getResult
    
    return  'return result' ;
};

export default getData;

Implementing Z-Clipping algorithm to basic 3D engine in Microsoft Makecode Arcade

I have made a basic 3D engine in microsoft makecode arcade, it currently renders a 3d cube that you can walk around and rotate, but the z-clipping is horrible and makes it an unpleasant experience. I want to implement something like they show in this scratch tutorial, but I’m not really good at that kind of stuff.
If you want to help, go to this link to edit the code

Thanks!

At first I tried to just not render a triangle if any one of its vertices were behind -140z, but that wasn’t very visually appealing as triangles disappear once they got close

Creating Typescript Module, Module Not Found Error Can’t Resolve. Incorrect Source Location?

I’ve created and published a Typescript package, an SDK for my API. I’ve not done this before, and used a lot of third party tools to do the heavy lifting. The end result, when installed from NPM, doesn’t work as expected. If I try to import a class from @namespace/module I get an error Cannot find module '@namespace/module' or its corresponding type declarations. If I import it as @namespace/module/dist/types/src/index that error goes away, but will instead get Module not found: Error: Can't resolve '@namespace/module/dist/types/src/index' when I try to compile.

I suspect I have something in the wrong location, or am missing a reference, but I cannot discover what that might be, as the third party tools picked those locations. Specifically, tomchen/example-typescript-package, but I also have a module that’s generating dynamic TypeScript based on my API.

dist folder contains cjs, esm, umd and types folders. cjs and esm have .js files in those, as well as /src, and /src/build/moduleName. types has .d.ts files in the same subfolders. umd has just index.js.

Node 18.18

Googling shows result for people having trouble installing correctly built modules, I’m assuming the error is in the module itself. As I’m not really sure what exactly is wrong, I’ve not had success finding any solution. My lack of experience creating modules is limiting me here.

NodeJS only fork on first import, after that return preset functions

I am trying to create a logger, which will spawn forks that periodically write stuff to files.
It will simply be imported with ‘import T from “path”‘, upon the first import it should spawn the forks and set the function, upon the second one and so on, those set functions should be returned.

f.e

// code

if (first execution) {
    const subprocess1 = child_process.fork(path);
    T = subprocess1.send(data) 
} else { /* ??????? */ }

export default T export { subfunctions };

Is this even possible within NodeJS on Windows?
Or do I have a fundamental misunderstanding of how forking works on Node?

Here is the current code I have:

"use strict";

const syncDate = Date.now();
const syncDateString = new Date(syncDate).toString().slice(0, 24).replace(/:/g, "-").replace(/ /g, "_");

const path = "./src/Services/Logger";

import { fork } from "child_process";

// ! Spawn subprocesses
const MainSubprocessPath = `${path}/MainSubprocess.js`;
const MainSubprocess = fork(MainSubprocessPath);

/**
 * Logs information to a filestream with timestamp, optional note, and parameters to the main log file.
 *
 * @param {string} data - The main data to be logged.
 * @param {string} [note] - An optional note to be included in the log.
 * @param {Array<[string, any]>} [parameters] - Parameters of the currently executing piece of code within data.
 *                                                For example, ["Abc", 2] will log as Abc=2.
 *
 * @returns {void}
 */
const T = (data, note, ...parameters) => MainSubprocess.send({ data, note, parameters });

T(`Starting program execution. [${syncDate} - ${syncDateString}]`);
MainSubprocess.on("spawn", () => T(`[LOGGER] - MainSubprocess spawned | PID: ${MainSubprocess.pid}`));
MainSubprocess.on("exit", (code, signal) => T(`MainSubprocess exited with code: ${code} | signal: ${signal} | path: ${MainSubprocessPath}`));

// ! CONSOLE LOGGER !
const ConsoleSubprocessPath = `${path}/ConsoleSubprocess.js`;
const ConsoleSubprocess = fork(ConsoleSubprocessPath);
ConsoleSubprocess.on("spawn", () => T(`[LOGGER] - ConsoleSubprocess spawned | PID: ${ConsoleSubprocess.pid}`));
ConsoleSubprocess.on("exit", (code, signal) => T(`ConsoleSubprocess exited with code: ${code} | signal: ${signal} | path: ${ConsoleSubprocessPath}`));

/**
 * Pipe console output into a file.
 *
 * @param {string} data - Data which is saved to the file.
 *
 * @returns {void}
 */
const C = data => ConsoleSubprocess.send({ data });

// ! ERROR LOGGER !
const ErrorSubprocessPath = `${path}/ErrorSubprocess.js`;
const ErrorSubprocess = fork(ErrorSubprocessPath);
ErrorSubprocess.on("spawn", () => T(`[LOGGER] - ErrorSubprocess spawned | PID: ${ErrorSubprocess.pid}`));
ErrorSubprocess.on("exit", (code, signal) => T(`ErrorSubprocess exited with code: ${code} | signal: ${signal} | path: ${ErrorSubprocessPath}`));

/**
 * Pipe all Relaxy-wide errors into this file for easier diagnosis.
 *
 * @param {string} data - Data which is saved to the file.
 *
 * @returns {void}
 */
const E = data => ErrorSubprocess.send({ data });

// ! SERVER MESSAGE LOGGER !
const MainMessageSubprocessPath = `${path}/MainMessageSubprocess.js`;
const MainMessageSubprocess = fork(MainMessageSubprocessPath);
MainMessageSubprocess.on("spawn", () => T(`[LOGGER] - MainMessageSubprocess spawned | PID: ${MainMessageSubprocess.pid}`));
MainMessageSubprocess.on("exit", (code, signal) => T(`MainMessageSubprocess exited with code: ${code} | signal: ${signal} | path: ${MainMessageSubprocessPath}`));

/**
 * Pipe all messages on all servers into this file.
 *
 * @param {string} data - Data which is saved to the file.
 *
 * @returns {void}
 */
const M = data => MainMessageSubprocess.send({ data });

// ! DMS LOGGER !
const DMMessageSubprocessPath = `${path}/DMMessageSubprocess.js`;
const DMMessageSubprocess = fork(DMMessageSubprocessPath);
DMMessageSubprocess.on("spawn", () => T(`[LOGGER] - DMMessageSubprocess spawned | PID: ${DMMessageSubprocess.pid}`));
DMMessageSubprocess.on("exit", (code, signal) => T(`DMMessageSubprocess exited with code: ${code} | signal: ${signal} | path: ${DMMessageSubprocessPath}`));

/**
 * Pipe all DMs Relaxy Receives onto this file.
 *
 * @param {string} data - Data which is saved to the file.
 *
 * @returns {void}
 */
const dM = data => DMMessageSubprocess.send({ data });

// Exports
export default T;
export { T, C, E, M, dM, syncDate, syncDateString };

T("[LOGGER] - init finished.");

Here is what I’ve tried doing:

  1. Add a fs.writeFileSync and then check at the top whether the file is more than X kb
  2. Create a singleton:
let instance = null;

const init = () => { 
    // all of the code here
    return { T, C, E, M, dM, syncDate, syncDateString };
}


export default instance || (instance = init());

Tried looking up how to check for existing forks by PID or stuff but no luck. I’d appreciate if anyone would help me here, I’ll read anything you throw at me.

JS Code not executing after refresh action

My app currently has a dynamic action that triggers on the change of a select list item and contains three events:

  1. Refresh of an Interactive Grid

This is important because the interactive grid source query contains the value of the select list in its where clause.

  1. Execute PL/SQL code, pulls some table data
  2. Execute JS Code, takes some values from action 2 and then selects certain rows in the interactive grid that was refreshed in step 1 by using view.setSelectedRecords()

This works perfectly fine without the refresh as the same thing happens in other places within the same oracle page, but when I add the refresh action the rows don’t get selected and as far as I can tell from some console.log() debugging, everything gets ran, but the rows don’t get selected.

I have tried using the “after refresh” dynamic action for the second two events but this does not work either, I think it is because after refresh isn’t supported for IG but I’m not positive.

I also have the “Fire on Initialization option unchecked for all three of my actions”

Any help would be greatly appreciated.

need unique ip address output to different users on node.js?

i need help in getting unique ip address on node.js or javascript with this code below, searched all over for working codes but couldn’t get unique outputs it keeps giving me the same ip output to 4 different users i send email to:

const randomIp = () => Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join('.');

randomIp();     //e.g 175.89.174.131

so all 4 users keeps getting

user1 output: 175.89.174.131

user2 output: 175.89.174.131

user3 output: 175.89.174.131

user4 output: 175.89.174.131

i need it to be unique please help me correct the code or at the functions that makes it unique on node.js

thank you <3

Snippet for input form autofill in Javascript (Chrome)

I am trying to learn how to automate the input values in some forms when they get repetitive (asking for age, gender, location).

I have investigated the HTML and noticed there are also a few hidden bits (which I unhidden for the screenshot below):

enter image description here

I have never worked with KnockoutJS before and it is not as simple as previous examples I worked on.

For the time being, I managed to create the following for 1 question only:

document.getElementById("sq_101i").value = "26";

 document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("sq_101i").value = "26";
});

But when I do this for the radio buttons, it does not work:

var radioButtons = document.querySelectorAll('.sv_q_radiogroup_control_item');

for (var i = 0; i < radioButtons.length; i++) {
    if (radioButtons[i].value == "Male") {
        radioButtons[i].checked = true;
        break;
    }
}

document.addEventListener("DOMContentLoaded", function() {
            var radioButtons = document.querySelectorAll('.sv_q_radiogroup_control_item');

            for (var i = 0; i < radioButtons.length; i++) {
                if (radioButtons[i].value == "Male") {
                    radioButtons[i].checked = true;
                    break;
                }
            }
        });

Even if I try for the specific question:

var radioButton = document.querySelectorAll('#sq_101i > .sv_q_radiogroup_control_item');

for (var i = 0; i < radioButton.length; i++) {
    if (radioButton[i].value == "Male") {
        radioButton[i].checked = true;
        break;
    }
}

document.addEventListener("DOMContentLoaded", function() {
            var radioButton = document.querySelectorAll('#sq_101i > .sv_q_radiogroup_control_item');

            for (var i = 0; i < radioButton.length; i++) {
                if (radioButton[i].value == "Male") {
                    radioButton[i].checked = true;
                    break;
                }
            }
        });

The outerHTML of one specific radio button is pasted below:

<div data-bind="css: question.getItemClass(item)" class="sv_q_radiogroup sv-q-col-1">
            <label data-bind="css: question.koCss().label" class="sv_q_radiogroup_label">
                <input type="radio" data-bind="attr: {name: question.name + '_' + question.id, value: item.value, id: ($index() == 0) ? question.inputId : '', 'aria-label': question.locTitle.renderedHtml}, checked: question.koValue, enable: !question.koIsReadOnly(), css: question.koCss().itemControl" name="question25_sq_100" value="item1" id="sq_100i" aria-label="1. With what gender do you identify?" class="sv_q_radiogroup_control_item">
                <span data-bind="css: question.koCss().materialDecorator" class="circle"></span>
                <span class="check"></span>
    <span style="position: static;" data-bind="text: koRenderedHtml">Male</span>
                </span>
            </label>
        </div>

My target is to automate the whole thing. To have one code for all the checkboxes with multiple IF statements and then do something like this to automatically answer if the question contains a keyword (e.g. age, name etc):

const myself = { Name: "Doctor Who", Age: "26"};

for (const [key, value] of Object.entries(myself)) {
  const target = [...h3].find(el => el.textContent.includes(key));
  if (target) {
    target.nextElementSibling.value = value;
  }
}

Need help converting Javscript to JQuery

Maybe i’m just lazy not understanding JQuery that well but i’m a bit in a hurry and think Vanilla JS is just easier for me to grasp creating things with.

I have created a ul consisting of li’s, each consisting with a special product with all the attributes related to it.

I have 2 buttons in the HTML that let’s users navigate through different products (Featured Products) on the page. The buttons trigger the buttonPress() function below.

The products are stored in the Array below.
This code works perfect but needs to be in JQuery syntax.

Thanks in advance.

JS Code:

var products = 
    [
        {
            "id": 1,
            "url": "https://swiftwintekstore.com/products/type-c-usb-3-2-gen2-pcie-card-hub-usb-3-0-pci-express-board-pci-e-pci-e-usb-3-adapter-multiplier-usb3-3-1-controller-riser-cards",
            "rel": "Product page of a Type C USB 3.2 Gen2 PCIE Card Hub USB",
            "title": "Type C USB 3.2 Gen2 PCIE Card Hub",
            "desc": "Type C USB 3.2 Gen2 PCIE Card Hub USB 3.0 Adapter Multiplier USB3 3.1 Controller Riser Cards",
            "discount_amt": 18.2
        },
        { 
            "id": 2,
            "url": "https://swiftwintekstore.com/products/super-si-pro-silicon-fast-charger-mobile-phone-30w",
            "rel": "Product page of a Super Si Pro Silicon Fast Charger Mobile Phone 30W",
            "title": "Super Si Pro Silicon Fast Charger Mobile 30W",
            "desc": "Super Si Pro Silicon Fast Charger Mobile Phone 30W",
            "discount_amt": 7.14
        },
        { 
            "id": 3,
            "url": "https://swiftwintekstore.com/products/zoerax-rj45-pass-through-crimper-for-cat6a-cat6-cat5-cat5e-ethernet-connector-all-in-one-crimp-tool",
            "rel": "Product page of the ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
            "title": "ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
            "desc": "ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
            "discount_amt": 25.0
        },
        { 
            "id": 4,
            "url": "https://swiftwintekstore.com/products/zoerax-network-cable-tester-rj45-rj11-cat5-tool-test-ethernet-telephone-cables?variant=47704487297362",
            "rel": "Product page of the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool",
            "title": "ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool",
            "desc": "Ensure your CAT cables are working correctly. Get the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool with this <strong>Huge</strong> discount!",
            "discount_amt": 41.6
        },
        {
            "id": 5,
            "url": "https://swiftwintekstore.com/products/zoerax-all-in-one-pass-through-crimper-for-rj45-rj12-rj11-network-connectors-cat5-5e-6-6a-7?_pos=3&_sid=0cc4887e8&_ss=r",
            "rel": "Product page of the ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
            "title": "ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
            "desc": "ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
            "discount_amt": 19.3
        },
        {
            "id": 6,
            "url": "https://swiftwintekstore.com/products/mini-magnetic-power-bank-10000mah-external-battery",
            "rel": "Product-page-of-a-magnetic-power-bank",
            "title": "mini-magnetic-power-bank-10000mah-external-battery",
            "desc": "New Power Banks in stock, 10000mAh 15WPD",
            "discount_amt": 7.13
        },
        {
            "id": 7,
            "url": "https://swiftwintekstore.com/products/electric-household-small-coffee-automatic-cream-stirrer",
            "rel": "Product-page-of-an-automatic-coffee-cream-stirrer",
            "title": "coffee-automatic-cream-stirrer",
            "desc": "Coffee drinker? Don't miss out on this product",
            "discount_amt": 11.7
        },
        {
            "id": 8,
            "url": "https://swiftwintekstore.com/products/compact-bluetooth-photo-tag-sticker-thermal-printer-for-on-the-go-printing",
            "rel": "Product page of a mobile bluetooth photo printer",
            "title": "compact bluetooth photo sticker printer",
            "desc": "Compact Bluetooth Photo Tag Sticker Thermal Printer for On-the-Go Printing",
            "discount_amt": 15
        },
        {
            "id": 9,
            "url": "https://swiftwintekstore.com/products/zoerax-nvme-pro-adapter-pcie-4-0-ssd-to-desktop-pc-64gbps-m-2-nvme-ssd?variant=47704764809554",
            "rel": "Product page for the ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
            "title": "ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
            "desc": "ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
            "discount_amt": 30
        },
        {
            "id": 10,
            "url": "https://swiftwintekstore.com/products/2-5gbps-pci-e-network-card-stable-wired-connection-for-high-speed-performance-compatible-with-gigabit-ethernet-networks-ce-certified",
            "rel": "Product page of a 2.5Gbps PCI-E Network Card",
            "title": "2.5gbps PCIe network card - CE certified",
            "desc": "2.5Gbps PCI-E Network Card - Stable Wired Connection for High-Speed Performance - Compatible with Gigabit Ethernet Networks - CE Certified",
            "discount_amt": 0
        }
    ];
let add_new_items = true;

// user pressed the left OR Right Chevron button. Replace the 'ul' content
// with new li's consisting of the Object attributes in the Array above.
const buttonPress = () => {
  if (add_new_items) {
    add_products((start_index = 0), (end_index = products.length / 2));
    add_new_items = false;
  } else {
    add_products((start_index = 5), (end_index = products.length));
    add_new_items = true;
  }
};

const add_products = (start_index, end_index) => {
  var products_container = document.getElementById("featured-prod-container");
  products_container.innerHTML = "";
  for (let index = start_index; index < end_index; index++) {
    const product = products[index];
    li = document.createElement("li");
    li.innerHTML = `<li class="product-all" id=${product.id}>
      <a class="in-stock-links" href="${product.url}"
          rel="${product.rel}" title="${product.title}">
          <p class="product-desc">
              ${product.desc}
          </p>
          <p class="discount-amount">
              <span class="now">Now ${product.discount_amt}% Off </span>
          </p>
      </a>
      </li>`;
    products_container.appendChild(li);
  }
};

I have tried converting to Jquery syntax but doesn’t get it to work.

Making an infinite drag and drop source HTML

I am a noob in javascript, and I want a drag and drop to have infinite sources to drag and drop. So, there is an image to drag, then drop elsewhere. When you drop it elsewhere, the original image stays there and another image appears where you dropped it.
I tried to clone it, but it didn’t work, and I feel like there is a better way.

Javascript:

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  let clone = ev.cloneNode(true);
  var data = clone.dataTransfer.getData("text");
  clone.target.appendChild(document.getElementById(data));
}

HTML:

<li ondrop = "drop(event)" ondragover = "allowDrop(event)">ex1</li>
<li ondrop = "drop(event)" ondragover = "allowDrop(event)">ex2</li>
<li ondrop = "drop(event)" ondragover = "allowDrop(event)">ex3</li>
<img src = "images/img1.png" draggable = "true" ondragstart = "drag(event)">

None of the questions on the internet answered this question (at least that I could find). Also, if possible, please find a way that you can control each dropped image.

Google Maps markers don’t appear with XML data

I’m trying to build a Google Maps app that reads data from an XML file using XMLHttpRequest(). I can read the data fine. The console.log output is, for example:

14.999167, 145.619444

The map and first marker appear, but none of the data inside getXML() creates markers. I don’t understand what I’m doing wrong. Here’s the Javascript:

let map;
async function initMap() {
        const myLatLng = { lat: 36.7, lng: -95.2 }
        const { Map } = await google.maps.importLibrary("maps");
        map = new Map(document.getElementById("map"), {center:myLatLng , zoom: 4, gestureHandling:'greedy'});
        new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", });
        getXML();
} 

function getXML() {
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.onload=function() {
                var xmlDoc = xmlhttp.responseXML;
                var xmlrows = xmlDoc.documentElement.getElementsByTagName("marker");
                for (var i = 0; i < xmlrows.length; i++) {
                        var xmlrow = xmlrows[i];
                        var name = xmlrow.getElementsByTagName("name") [0].firstChild.data;;
                        var geo  = xmlrow.getElementsByTagName("geo") [0].firstChild.data;
                        console.log(geo);
                        var LatLng = new google.maps.LatLng(geo);
                        new google.maps.Marker({position: LatLng, map});
                        }
                }
        xmlhttp.open("GET","ww2.xml",true);
        xmlhttp.send();
}

initMap();

custom div resizing start lagin over time next.js

this is my code for app with custom window resizing

note.tsx:

import {
  useState,
  useCallback,
  useRef,
  useEffect,
  memo,
  useLayoutEffect,
} from "react";
import Editor from "./editor/editor";
import Preview from "./preview/preview";
import { Container, NoteSection, Resizer } from "./style";
import Header from "./header/header";
import { ViewMode } from "./types";
import { debounce } from "lodash";

interface Props {
  width: string;
}
const Note = memo((props: Props) => {
  const { width } = props;

  const [doc, setDoc] = useState<string>("# Hello, World!n");
  const [mode, setMode] = useState<ViewMode>(ViewMode.Middle);
  const [editWidth, setEditWidth] = useState("50%");
  const [viewWidth, setViewWidth] = useState("50%");

  const handleDocChange = useCallback((newDoc: string) => {
    setDoc(newDoc);
  }, []);

  const resizerRef = useRef<HTMLDivElement>(null);
  const [isResizing, setIsResizing] = useState(false);

  const handleMouseDown = useCallback(() => {
    setIsResizing(true);
  }, []);

  const handleMouseMove = useCallback(
    debounce((event: MouseEvent) => {
      if (!isResizing) return;
      const resizer = resizerRef.current;
      if (!resizer) return;

      const container = resizer.parentNode as HTMLElement;
      const containerRect = container.getBoundingClientRect();

      const mousePosition = event.clientX - containerRect.left;

      const viewWindowWidth = containerRect.width - mousePosition;

      if (viewWindowWidth > 100 && mousePosition > 100) {
        requestAnimationFrame(() => {
          setEditWidth(mousePosition.toString() + "px");
          setViewWidth(viewWindowWidth.toString() + "px");
        });
      }
    }, 5),
    [isResizing]
  );

  const handleMouseUp = useCallback(() => {
    setIsResizing(false);
  }, []);

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
  }, [handleMouseMove]);

  useLayoutEffect(() => {
    if (mode == ViewMode.Middle) {
      setEditWidth(`${editWidth}`);
      setViewWidth(`${viewWidth}`);
    }
  }, [mode]);

  return (
    <NoteSection $width={width}>
      <Header setMode={setMode} mode={mode} width={width} />
      <Container $width={width}>
        <Editor
          onChange={handleDocChange}
          initialDoc={doc}
          mode={mode}
          width={editWidth}
        />
        <Resizer ref={resizerRef} onMouseDown={handleMouseDown} $mode={mode} />
        <Preview doc={doc} mode={mode} width={viewWidth} />
      </Container>
    </NoteSection>
  );
});

export default Note;

page.tsx:

"use client";
import React, { useState, useRef, useCallback, useEffect } from "react";
import Title from "./title/title";
import Note from "./note/note";
import Menu from "./menu/menu";
import { Main, Resizer } from "./style";
import { debounce } from "lodash";

const Home = () => {
  const [menuWidth, setMenuWidth] = useState("197px");

  const resizerRef = useRef<HTMLDivElement>(null);
  const [isResizing, setIsResizing] = useState(false);

  const handleMouseDown = useCallback(() => {
    setIsResizing(true);
  }, []);

  const handleMouseMove = useCallback(
    debounce((event: MouseEvent) => {
      if (!isResizing) return;
      const resizer = resizerRef.current;
      if (!resizer) return;

      const container = resizer.parentNode as HTMLElement;
      const containerRect = container.getBoundingClientRect();

      const mousePosition = event.clientX - containerRect.left;

      let rightWidth = containerRect.width - mousePosition;

      if (rightWidth < (window.innerWidth / 4) * 2.7) {
        rightWidth = (window.innerWidth / 4) * 2.7;
      }
      if (rightWidth > (window.innerWidth / 4) * 2.7 && mousePosition > 100) {
        requestAnimationFrame(() => {
          setMenuWidth((mousePosition - 3).toString() + "px");
        });
      }
    }, 5),
    [isResizing]
  );

  const handleMouseUp = useCallback(() => {
    setIsResizing(false);
  }, []);

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);

    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
  }, [handleMouseMove]);

  return (
    <>
      <Title />
      <Main>
        <Menu width={menuWidth} />

        <Note width={menuWidth} />

        <Resizer
          ref={resizerRef}
          onMouseDown={handleMouseDown}
          $width={menuWidth}
        />
      </Main>
    </>
  );
};

export default Home;

page-style.ts:

import styled from "styled-components";

export const Main = styled.main`
  display: flex;
`;

export const Resizer = styled.div<{ $width: string }>`
  position: absolute;
  background: #000;
  width: 3px;
  height: calc(100% - 31px);
  zindex: 1000;
  left: ${(props) => props.$width};
  top: 31px;
  cursor: col-resize;
  margin: 0 0px;
`;

note-style.ts:

import styled from "styled-components";
import { ViewMode } from "./types";

export const NoteSection = styled.div<{ $width: string }>`
  margin-left: ${({ $width }) => $width};
`;

export const Container = styled.div<{ $width: string }>`
  position: absolute;
  top: 56px;
  display: flex;
  width: calc(100% - ${({ $width }) => $width});
  height: calc(100% - 56px);
`;

export const Resizer = styled.div<{ $mode: ViewMode }>`
  background: #000;
  width: 3px;
  cursor: col-resize;
  margin: 0 1px;
  display: ${({ $mode }) => ($mode === ViewMode.Middle ? "block" : "none")};
`;

so when i start app, first minute it works fine, but over time window resizing starts laging and it becomes imposible to resize divs

can be this fixed?
i used everything that i was able to found with google and ai