How change icon on a button dynamically with JavaScript after 2 seconds when clicked?

The main purpose of my script is to announce that the copy of the text has been successfully completed.

When I click on the button, the first icon change was ok, as is the toast display, and the text is correctly copied with the framework clipboard.js.

<button class="btn btn-outline-success" id="url-rss" data-clipboard-text="Texte à copier">
      <i class="fa-regular fa-clipboard" id="icon"></i>
</button>

when i click on the button, 2 secondes after, I want the script change the button again to fa-circle-check to fa-clipboard.

I use clipboard.js, Bootstrap 5 (bundle) & Font Awesome.

This is my script :

document.addEventListener('DOMContentLoaded', function () {
    // Load of Clipboard.js
    let clipboard = new ClipboardJS('#url-rss')

    // Variable for the Toast with Bootstrap 5
    let toastCopie = new bootstrap.Toast(document.querySelector('#copieToast'), {
        animation: true,
        delay: 2500
    });

    // We listen #url-rss on click
    document.querySelector('#url-rss').addEventListener('click', async function() {
        // If Click on the <button> do a Toast()
        toastCopie.show()

        let iconElement = document.querySelector('#icon')

        // Change of the icon, first round
        iconElement.classList.remove('fa-clipboard')
        iconElement.classList.add('fa-circle-check')

        await new Promise(resolve => setTimeout(resolve, 2000));

        // Chnage of the icon, second round
        iconElement.classList.remove('fa-circle-check');
        iconElement.classList.add('fa-clipboard');
    })
});

I have copy an example of my script on codepen if anyone want try.

I have try with this too :

        setTimeout(function() {
            iconElement.classList.remove('fa-circle-check');
            iconElement.classList.add('fa-clipboard');
        }, 2000);

But after various attempts and research, my JavaScript skills aren’t advanced enough for me to solve this problem on my own.

Cannot read properties of undefined (reading ‘executeScript’) for Chrome extension

I made a chrome extension that worked perfectly up until a few weeks ago. Now when I run it, I get this error. This wasn’t present before. I’m unsure as to why it’s not working considering I have all the needed permissions in my JSON. Can anyone provide help?

Cannot read properties of undefined (reading 'executeScript')
Background.js
chrome.tabs.executeScript({
  code: "window.getSelection().toString();"
}, function (selection) {
  const selectedText = selection[0];
  const resultSentence = removeStopWords(selectedText);
  document.getElementById("new-task").innerHTML = resultSentence;

{
  "manifest_version": 3,
  "name": ""
  "version": "",
  "description": "",
  "permissions": [
    "activeTab",
    "scripting",
    "tabs",
    "storage"
  ],
  "action": {
    "default_popup": "index.html",
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "background": {
    "service_worker": "background.js"
  }
}

start task, async await later retrieve values. Only works with specific order [duplicate]

Im running into an issue where in the following 2 async calls the order of then must be async1 -> async2 and the awaits have to match await 1 -> 2 otherwise errors aren’t caught.

Must be this order

const async1 = convertImage(pp, uid, false);
const async2 = hash(password, 10);
imgRef = await async1;
hashedPass = await async2;

any other ordering of the statements causes the code to fail. By throwing errors that cannot be caught. Even with try catch.
So everything is bypassed and it returns

Error: Invalid base64 string:

Where hash is from the bcrypt library and convertImage is:

async function convertImage(
    base64: string,
    key: string,
    remove: boolean
): Promise<string> {
    if (base64 === '') {
        console.log('fail');
        throw new Error(`Invalid base64 string: ${base64}`);
    }
    return '';

Decreasing value by given steps in non-linear way

I need to decrease a value in X steps from max to min value. The easy part would be this:

const data = []
const x = 6
const factor = (max - min) / x
for (let index = 1; index <= x; index++) {
    data.push(max - index * factor)
}

This would give me a linear result assuming there are 6 steps: [20, 17.5, 15, 12.5, 10, 7.5, 5] where max is 20 and min is 5.

Unfortunately I need no linear values. First there should be fast decreasing values and at the end it should get more slowly decreasing.
Ok, for that the resolution of only 6 steps is a bad example. But the problem is the same to me: How can I calculate a more ‘logarithmic’ decrease? I mean something like [20, 11, 9, 7, 6, 5]. This is just an estimated example. I don’t know how to explain it better…

Pass arguments or parameters to a class in JavaScript

I am sorry if I do not have the terminology correct, but I am trying to pass arguments to change the options in a JavaScript class and I do not know how. I want to be able to change the background and fill properties when initiating it. My tech stack is node.js, webpack, gulp, javascript, pug, and gasp.

Here is the object that I need to pass to:

export default class WaveSingle {
    constructor(container, options = {}) {
        this.container = container;

        this.opts = {
            background: 0x000000,
            fill: 0xffffff,
            ...options,
        };

Initiating the object:

import {Component} from 'bona';
import {magicBatchSlideElementAppear} from '../lib/transitions';
import WaveSingle from '../lib/WaveSingle';

export default class FormHero extends Component {
    constructor() {
        super(...arguments);

        this.scene = this.el.querySelector('.form-hero-bg-scene');
        this.col = this.el.querySelectorAll('.form-hero-grid-col');
    }

    async onInit() {
        await document.fonts.ready;

        this.initWave();
    }

    initWave() {
        this.wave = new WaveSingle(this.scene);
    }
}

How do I change the properties of background and fill in WaveSingle via:

this.wave = new WaveSingle(this.scene);

How can I add balls to my bouncy ball simulator? [closed]

Right now, I’m trying to create a bouncy ball project. I currently have a set amount of white balls that bounce around.

Question 1: How can I create an “add ball” button so that when I hit it, another bouncy ball is created?

Question 2: How can I give my balls color? I tried doing it and they just stayed white.

Question 3 (optional): How can I make it so that after every collision with another ball or the wall, the color of the ball changes (if two balls collide, both colors change. If a ball hits the wall, the color of the ball changes).

Important Note: WE obviously can’t have too many balls (my poor school Chromebook couldn’t handle too much) so the MAXIMUM number of balls should be 100.

Side note: I did copy some of this from other people, so I don’t completely understand how all of the code works together. It’s very messy and mostly not my style.

function lineMessage(msg) {
    document.querySelector('#myMessage').textContent += msg + '. ';
}

function groupMessage(msg) {
    document.querySelector('#myMessage').innerHTML += msg + '<br/>';
}

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext("2d");
canvas.width = 1000;
canvas.height = 550;

const gravity = 0;
const wallLoss = 1;
const ballCount = 20;  // approx as will not add ball if space can not be found
const minBallSize = 13;
const maxBallSize = 20;
const velMin = 1;
const velMax = 5; 
const maxResolutionCycles = 100;

Math.TAU = Math.PI * 2;
Math.rand = (min, max) => Math.random() * (max - min) + min;
Math.randI = (min, max) => Math.random() * (max - min) + min | 0; // only for positive numbers 32bit signed int
Math.randItem = arr => arr[Math.random() * arr.length | 0]; // only for arrays with length < 2 ** 31 - 1
// contact points of two circles radius r1, r2 moving along two lines (a,e)-(b,f) and (c,g)-(d,h) [where (,) is coord (x,y)]
Math.circlesInterceptUnitTime = (a, e, b, f, c, g, d, h, r1, r2) => { // args (x1, y1, x2, y2, x3, y3, x4, y4, r1, r2)
    const A = a * a, B = b * b, C = c * c, D = d * d;
    const E = e * e, F = f * f, G = g * g, H = h * h;
    var R = (r1 + r2) ** 2;
    const AA = A + B + C + F + G + H + D + E + b * c + c * b + f * g + g * f + 2 * (a * d - a * b - a * c - b * d - c * d - e * f + e * h - e * g - f * h - g * h);
    const BB = 2 * (-A + a * b + 2 * a * c - a * d - c * b - C + c * d - E + e * f + 2 * e * g - e * h - g * f - G + g * h);
    const CC = A - 2 * a * c + C + E - 2 * e * g + G - R;
    return Math.quadRoots(AA, BB, CC);
}  

Math.quadRoots = (a, b, c) => { // find roots for quadratic
    if (Math.abs(a) < 1e-6) {
        return b != 0 ? [-c / b] : [] 
    }

    b /= a;
    var d = b * b - 4 * (c / a);

    if (d > 0) {
        d = d ** 0.5;
        return  [0.5 * (-b + d), 0.5 * (-b - d)]
    }

    return d === 0 ? [0.5 * -b] : [];
}

Math.interceptLineBallTime = (x, y, vx, vy, x1, y1, x2, y2, r) => {
    const xx = x2 - x1;
    const yy = y2 - y1;
    const d = vx * yy - vy * xx;

    if (d > 0) {  // only if moving towards the line
        const dd = r / (xx * xx + yy * yy) ** 0.5;
        const nx = xx * dd;
        const ny = yy * dd;
        return (xx * (y - (y1 + nx)) - yy * (x -(x1 - ny))) / d;
    }
}

const balls = [];
const lines = [];

function Line(x1, y1, x2, y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
}

Line.prototype = {
    draw() {
        ctx.moveTo(this.x1, this.y1);
        ctx.lineTo(this.x2, this.y2);
    },
    reverse() {
        const x = this.x1;
        const y = this.y1;
        this.x1 = this.x2;
        this.y1 = this.y2;
        this.x2 = x;
        this.y2 = y;
        return this;
    }
}
    
function Ball(x, y, vx, vy, r = 45, m = 4 / 3 * Math.PI * (r ** 3)) {
    this.r = r;
    this.m = m;
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
}

Ball.prototype = {
    update() {
        this.x += this.vx;
        this.y += this.vy;
        this.vy += gravity;
    },
    draw() {
        ctx.moveTo(this.x + this.r, this.y);
        ctx.arc(this.x, this.y, this.r, 0, Math.TAU);
    },
    interceptLineTime(l, time) {
        const u = Math.interceptLineBallTime(this.x, this.y, this.vx, this.vy, l.x1, l.y1, l.x2, l.y2, this.r);
        if (u >= time && u <= 1) {
            return u;
        }
    },
    checkBallBallTime(t, minTime) {
        return t > minTime && t <= 1;
    },
    interceptBallTime(b, time) {
        const x = this.x - b.x;
        const y = this.y - b.y;
        const d = (x * x + y * y) ** 0.5;

        if (d > this.r + b.r) {
            const times = Math.circlesInterceptUnitTime(
                this.x, this.y, 
                this.x + this.vx, this.y + this.vy, 
                b.x, b.y,
                b.x + b.vx, b.y + b.vy, 
                this.r, b.r
            )

            if (times.length) {
                if (times.length === 1) {
                    if (this.checkBallBallTime(times[0], time)) {
                        return times[0]
                    }

                    return;
                }

                if (times[0] <= times[1]) {
                    if (this.checkBallBallTime(times[0], time)) {
                        return times[0]
                    }

                    if (this.checkBallBallTime(times[1], time)) {
                        return times[1]
                    }

                    return
                }

                if (this.checkBallBallTime(times[1], time)) { 
                    return times[1]
                }      

                if (this.checkBallBallTime(times[0], time)) {
                    return times[0]
                }
            }
        }
    },
    collideLine(l, time) {
        const x1 = l.x2 - l.x1;
        const y1 = l.y2 - l.y1;
        const d = (x1 * x1 + y1 * y1) ** 0.5;
        const nx = x1 / d;
        const ny = y1 / d;            
        const u = (this.vx  * nx + this.vy  * ny) * 2;
        this.x += this.vx * time;   
        this.y += this.vy * time;   
        this.vx = (nx * u - this.vx) * wallLoss;
        this.vy = (ny * u - this.vy) * wallLoss;
        this.x -= this.vx * time;
        this.y -= this.vy * time;
    },
    collide(b, time) {
        const a = this;
        const m1 = a.m;
        const m2 = b.m;
        const x = a.x - b.x
        const y = a.y - b.y  
        const d = (x * x + y * y);
        const u1 = (a.vx * x + a.vy * y) / d
        const u2 = (x * a.vy - y * a.vx ) / d
        const u3 = (b.vx * x + b.vy * y) / d
        const u4 = (x * b.vy - y * b.vx ) / d
        const mm = m1 + m2;
        const vu3 = (m1 - m2) / mm * u1 + (2 * m2) / mm * u3;
        const vu1 = (m2 - m1) / mm * u3 + (2 * m1) / mm * u1;
        a.x = a.x + a.vx * time;
        a.y = a.y + a.vy * time;
        b.x = b.x + b.vx * time;
        b.y = b.y + b.vy * time;
        b.vx = x * vu1 - y * u4;
        b.vy = y * vu1 + x * u4;
        a.vx = x * vu3 - y * u2;
        a.vy = y * vu3 + x * u2;
        a.x = a.x - a.vx * time;
        a.y = a.y - a.vy * time;
        b.x = b.x - b.vx * time;
        b.y = b.y - b.vy * time;
    },
    doesOverlap(ball) {
        const x = this.x - ball.x;
        const y = this.y - ball.y;
        return  (this.r + ball.r) > ((x * x + y * y) ** 0.5);  
    }       
}

function canAdd(ball) {
    for (const b of balls) {
        if (ball.doesOverlap(b)) {
            return false
        }
    }

    return true;
}

function create(bCount) {
    lines.push(new Line(-10, 10, ctx.canvas.width + 10, 5));
    lines.push((new Line(-10, ctx.canvas.height - 2, ctx.canvas.width + 10, ctx.canvas.height - 10)).reverse());
    lines.push((new Line(10, -10, 4, ctx.canvas.height + 10)).reverse());
    lines.push(new Line(ctx.canvas.width - 3, -10, ctx.canvas.width - 10, ctx.canvas.height + 10)); 

    while (bCount--) {
        let tries = 100;
        debugger

        while (tries--) {
            const dir = Math.rand(0, Math.TAU);
            const vel = Math.rand(velMin, velMax);
            const ball = new Ball(
                Math.rand(maxBallSize + 10, canvas.width - maxBallSize - 10), 
                Math.rand(maxBallSize + 10, canvas.height - maxBallSize - 10),
                Math.cos(dir) * vel,
                Math.sin(dir) * vel,
                Math.rand(minBallSize, maxBallSize),
            )

            if (canAdd(ball)) {
                balls.push(ball);
                break;
            }
        }
    }
}

function resolveCollisions() {
    var minTime = 0, minObj, minBall, resolving = true, idx = 0, idx1, after = 0, e = 0;
    
    while (resolving && e++ < maxResolutionCycles) { // too main ball may create very lone resolution cycle. e limits this
        resolving = false;
        minObj = undefined;
        minBall = undefined;
        minTime = 1;
        idx = 0;

        for(const b of balls) {
            idx1 = idx + 1;
            while (idx1 < balls.length) {
                const b1 = balls[idx1++];
                const time = b.interceptBallTime(b1, after);

                if (time !== undefined) {
                    if (time <= minTime) {
                        minTime = time;
                        minObj = b1;
                        minBall = b;
                        resolving = true;
                    }
                }
            }

            for (const l of lines) {
                const time = b.interceptLineTime(l, after);
                if (time !== undefined) {
                    if (time <= minTime) {
                        minTime = time;
                        minObj = l;
                        minBall = b;
                        resolving = true;
                    }
                }
            }

            idx ++;
        }

        if (resolving) {
            if (minObj instanceof Ball) {
                minBall.collide(minObj, minTime);
            } else {
                minBall.collideLine(minObj, minTime);
            }

            after = minTime;
        }
    }
}

create(ballCount);
mainLoop();

function mainLoop() {
    ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
    resolveCollisions();

    for (const b of balls) {
        b.update()
    }

    ctx.strokeStyle = "#000";
    ctx.beginPath();

    for (const b of balls) {
        b.draw()
    }

    for (const l of lines) {
        l.draw()
    }

    ctx.stroke();
    requestAnimationFrame(mainLoop);
}
#canvas {
    width: 1000px;
    height: 550px
}

#myConsole {
    background-color: black;
    color: white;
    min-height: 100px;
}
<!DOCTYPE html>
<html lang="en">

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE-edge">
        <meta name="viewport", content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Christian Davis">
        <link rel="stylesheet" href="styles.css">

        <title>Bouncy Balls</title>
    </head>

    <body>
        <canvas id="canvas"></canvas>
        <p id="myConsole">&gt;&nbsp;<span id="myMessage"></span></p>

        <script src="app.js"></script>
    </body>
</html>

“hello” path not found with the react-router-dom v6 and @types/react-router-dom v5.3.3

Main file:

    import React, { useContext, useEffect } from 'react';
import { Route, RouteProps, Routes, useLocation, useMatch } from 'react-router-dom';

import AuthenticationContext from './AuthenticationContext';

export type PrivateRouteProps = RouteProps & {
  Element?: React.ComponentType<any>;
};

/* eslint-disable react/jsx-props-no-spreading */
function PrivateRoute({ children, path, Element, ...routePropsWithoutChildrenAndComponent }: any) {
  const { authorize, authenticated, authenticating, callbackPath } =
    useContext(AuthenticationContext);
  const location = useLocation();

  const match = useMatch(path?.toString() || '*');

  useEffect(() => {
    if (!authenticated && !authenticating && match && location.pathname !== callbackPath) {
      const authorizeAsync = async () => {
        authorize(location as unknown as URL);
      };
      authorizeAsync();
    }
  }, [authorize, match, location, authenticated, authenticating, callbackPath]);

  if (!authenticated) {
    return null;
  }

  return (
    <Routes>
      <Route
        {...routePropsWithoutChildrenAndComponent}
        element={Element ? <Element /> : children}
      />
    </Routes>
  );
}

export default PrivateRoute;

Test file:

/* eslint-disable react/prop-types */
import React from 'react';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history';
import { unstable_HistoryRouter as Router } from 'react-router-dom';

import { PrivateRoute } from '..';
import AuthenticationContext, { AuthenticationContextProps } from '../AuthenticationContext';

describe('PrivateRoute', () => {
  function renderWithRouterAndContext(
    content: JSX.Element,
    // eslint-disable-next-line @typescript-eslint/ban-types
    { location, context } = {} as { location: string; context: object },
  ) {
    const history = createMemoryHistory({ initialEntries: [location] });
    const defaultContext: AuthenticationContextProps = {
      fetchToken: () => 'xyz' as any,
      callbackPath: '/oauth',
      setError: () => {},
      authenticated: false,
      authenticating: false,
      authorize: () => {},
      logout: () => {},
      getToken: () => 'xyz',
    };
    const wrapper = ({ children }: { children: React.ReactNode }) => (
      <AuthenticationContext.Provider value={{ ...defaultContext, ...context }}>
        <Router history={history as any}>{children}</Router>
      </AuthenticationContext.Provider>
    );
    return {
      ...render(content, { wrapper } as any),
      history,
    };
  }

  describe('when authenticated', () => {
    it('can render children', () => {
      const { container } = renderWithRouterAndContext(
        <PrivateRoute path="/hello">
          <h1>Hello</h1>
        </PrivateRoute>,
        { location: '/hello', context: { callbackPath: '/oauth', authenticated: true } },
      );
      expect(container.innerHTML).toBe('<h1>Hello</h1>');
    });

    it('can render a component', () => {
      function MyComponent() {
        return <h1>Hey</h1>;
      }
      // eslint-disable-next-line react/jsx-no-bind
      const { container } = renderWithRouterAndContext(<PrivateRoute component={MyComponent} />, {
        location: '/hello',
        context: { callbackPath: '/oauth', authenticated: true },
      });
      expect(container.innerHTML).toBe('<h1>Hey</h1>');
    });

    it('can invoke a render prop function', () => {
      const { container } = renderWithRouterAndContext(
        <PrivateRoute
          render={({ history, location }: any) => <p>{${history.length} ${location.pathname}}</p>}
        />,
        { location: '/hello', context: { callbackPath: '/oauth', authenticated: true } },
      );
      expect(container.innerHTML).toBe('<p>1 /hello</p>');
    });
  });

  describe('when unauthenticated', () => {
    const authorize = jest.fn();

    beforeEach(() => {
      jest.clearAllMocks();
    });

    describe('for a matching path', () => {
      it('checks user authorization and does not render anything', () => {
        const { container } = renderWithRouterAndContext(
          <PrivateRoute path="/hello">
            <h1>Hello</h1>
          </PrivateRoute>,
          {
            location: '/hello',
            context: { callbackPath: '/oauth', authenticated: false, authorize },
          },
        );
        expect(container.innerHTML).toBe('');
        expect(authorize).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/hello' }));
      });
    });

    describe('for an OAuth callback path', () => {
      it('does not check user authorization and does not render anything', () => {
        const { container } = renderWithRouterAndContext(
          <PrivateRoute path="/">
            <h1>Hello</h1>
          </PrivateRoute>,
          {
            location: '/oauth?code=xyz&state=foo',
            context: { callbackPath: '/oauth', authenticated: false, authorize },
          },
        );
        expect(container.innerHTML).toBe('');
        expect(authorize).not.toHaveBeenCalled();
      });
    });

    describe('for a non-matching path', () => {
      it('does not check user authorization', () => {
        renderWithRouterAndContext(
          <PrivateRoute path="/hello">
            <h1>Hello</h1>
          </PrivateRoute>,
          { location: '/hi', context: { callbackPath: '/oauth', authenticated: false, authorize } },
        );
        expect(authorize).not.toHaveBeenCalled();
      });
    });

    describe('when authentication is in progress', () => {
      it('does not check user authorization', () => {
        renderWithRouterAndContext(
          <PrivateRoute path="/hello">
            <h1>Hello</h1>
          </PrivateRoute>,
          {
            location: '/hi',
            context: {
              callbackPath: '/hello',
              authenticating: true,
              authorize,
            },
          },
        );
        expect(authorize).not.toHaveBeenCalled();
      });
    });
  });
});

With the new version of react-router-dom v6 and @types/react-router-dom v5.3.3, after resolving some errors with the code changes it was giving the “hello” path not found error.

Error:

console.warn
No routes matched location “/hello”

  31 |     );
  32 |     return {
> 33 |       ...render(content, { wrapper } as any),
     |                ^
  34 |       history,
  35 |     };
  36 |   }

● PrivateRoute › when authenticated › can render children

expect(received).toBe(expected) // Object.is equality

Expected: "<h1>Hello</h1>"
Received: ""

  44 |         { location: '/hello', context: { callbackPath: '/oauth', authenticated: true } },
  45 |       );
> 46 |       expect(container.innerHTML).toBe('<h1>Hello</h1>');
     |                                   ^
  47 |     });
  48 |
  49 |     it('can render a component', () => {

  at Object.<anonymous> (packages/auth/src/_tests_/PrivateRoute.test.tsx:46:35)

● PrivateRoute › when authenticated › can render a component

expect(received).toBe(expected) // Object.is equality

Expected: "<h1>Hey</h1>"
Received: ""

  56 |         context: { callbackPath: '/oauth', authenticated: true },
  57 |       });
> 58 |       expect(container.innerHTML).toBe('<h1>Hey</h1>');
     |                                   ^
  59 |     });
  60 |
  61 |     it('can invoke a render prop function', () => {

  at Object.<anonymous> (packages/auth/src/_tests_/PrivateRoute.test.tsx:58:35)

● PrivateRoute › when authenticated › can invoke a render prop function

expect(received).toBe(expected) // Object.is equality

Expected: "<p>1 /hello</p>"
Received: ""

  66 |         { location: '/hello', context: { callbackPath: '/oauth', authenticated: true } },
  67 |       );
> 68 |       expect(container.innerHTML).toBe('<p>1 /hello</p>');
     |                                   ^
  69 |     });
  70 |   });
  71 |
        

Appriciate some suggessions, Thanks in advance

tinymce create comment function does not read updated state

I have implemented an editor with tinymce package and I have the comments plug in. In addition I have built a functionality as follows: When a user select a text, I store it on a state variable in order to read it from the tiny’s built in create function and send all the data to my backend. Overall I want when a user select a text in order to create a comment, to send the highlighted text to my backend through the tiny’s create function but the create function only reads the initial state of the variable and does not read the updated value. The code id as below:

import { Editor as EditorMce } from "@tinymce/tinymce-react";
//... some imports

function Editor() {
let [highlightedText, setHighlightedText] = useState("");

  const tinycomments_create = (req, done, fail) => {
    const { content, createdAt } = req;

    console.log("highligt inside create function");
    console.log(highlightedText); //This is always an empy string, the initial value
//and does not update when user highlights a text

    fetch("my-backend-endpoint", {
      method: "POST",
      body: JSON.stringify({
        content,
        createdAt,
        highlightedText,
      }),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Failed to create comment");
        }
        return response.json();
      })
      .then((req2) => {
        const conversationUid = req2.id;
        done({ conversationUid });
      })
      .catch((e) => {
        fail(e);
      });
  };

//... some existing code and I return the component

<EditorMce
                value={session ? session.sessionText : ""}
                onEditorChange={handleOnEditorChange}
                init={{
                  init_instance_callback: (editor) => {
                    editor.on("MouseUp", function (e) {
                      if (e.view.getSelection().toString() !== "") {
                        setHighlightedText(e.view.getSelection().toString());
                      }
                    });
                  },
                  content_css: "writer",
                  height: "80%",
                  width: "95%",
                  plugins: [
                    "tinycomments",
                    "advlist",
                    "autolink",
                    "lists",
                    "link",
                    "image",
                    "charmap",
                    "preview",
                    "anchor",
                    "searchreplace",
                    "visualblocks",
                    "code",
                    "fullscreen",
                    "insertdatetime",
                    "media",
                    "table",
                    "code",
                    "help",
                    "wordcount",
                  ],
                  menubar: "file edit view insert format tools tc",
                  menu: {
                    tc: {
                      title: "Comments",
                      items: "addcomment showcomments deleteallconversations",
                    },
                  },
                  toolbar:
                    "undo redo | fontsizeinput fontfamily | blocks | " +
                    "bold italic forecolor backcolor | alignleft aligncenter " +
                    "alignright alignjustify | bullist numlist outdent indent | " +
                    "removeformat | addcomment showcomments | help",
                  content_style:
                    "body { font-family:Helvetica,Arial,sans-serif; font-size:16px }" +
                    ".tox-comments-visible span.tox-comment  { background-color: #90EE90!important; }.tox-comments-visible span.tox-comment--active { background-color: black; }",
                  tinycomments_create,
                  tinycomments_reply,
                  tinycomments_edit_comment,
                  tinycomments_delete,
                  tinycomments_delete_all,
                  tinycomments_delete_comment,
                  tinycomments_lookup,
                }}
              />
}

How can I update the value of highlightedText inside tinycomments_create. I have tried the useCallback hook with no result. Also I have tried to add the tinycomments_create inside a useEffect and set it every time the highlightedText updates but again with no results.
Any thoughts on that?

Writing a selector for CSS or jQuery when the attribute name contains a colon

I’ve been trying to figure out how to get KanjiVG to work for a bit now, and while I’m able to get the images to display, I’m having trouble manipulating them (specifically, highlighting the radical, which is identified using a custom kvg:radical attribute).

Here’s how I’m including the SVG file:

        <div id="svg-container"></div>
        <script>
            jQuery(document).ready(function() {
                // Load SVG file and insert it into the container
                jQuery.ajax({
                    url: "img/kanjivg/<?php echo str_pad($kanji->ucs, 5, '0', STR_PAD_LEFT);?>.svg",
                    dataType: "xml",
                    success: function(data) {
                        jQuery("#svg-container").html(data.documentElement);

                        // Modify SVG properties
                        jQuery("[kvg\:radical]").css("stroke", "red");
                    }
                });
            });
        </script>

It loads fine, but everything remains black. I tried putting the jQuery("[kvg\:radical]").css("stroke", "red"); line into the console to see if it would work, and it keeps selecting nothing, even though I’ve opened the file and confirmed the presence of said attribute.

I tried working around this with CSS as follows (using display: none; to make it patently obvious if the selector worked):

[kvg:radical] {
    display: none;
}

But it’s still showing up. Yet if I just tell it to do something to svg, svg g, or svg text, it works fine—it’s when I try to access selectors with colons in them that it develops a blind spot.

Using a function from another question to dump a list of attributes on the node in question, we produced the following:

jQuery('#kvg\:04ee4-g1').each(function(){
    jQuery.each(this.attributes, function(){
        if(this.specified){
            console.log(this.name, this.value);
        }
    });
});

The output of which was as follows:

[Log] id – "kvg:04ee4-g1"
[Log] kvg:element – "人"
[Log] kvg:position – "top"
[Log] kvg:radical – "general"

…so it knows the attribute exists, but it doesn’t seem to want to allow direct access to it.

I guess one workaround is to use the foreach to go through the nodes and perform its function if it finds an attribute ending in “radical”, but that feels like a horribly inefficient method of doing business here. Is there a way I can grab elements containing [kvg:radical] in JavaScript or CSS that will work properly?

Get values of json object and fill a datatable

can u help me with this code?

                eventClick: function(info) {
                     let text = info.event.extendedProps.procs;
                     var obj = text.split(";");
                     var stock_data = JSON.parse(JSON.stringify(obj));

                     $("#tblProcedimientos").DataTable({
                        destroy: true,
                        data: stock_data,
                        language: {
                           emptyTable: "No hay datos disponibles para mostrar",
                           zeroRecords: "No hay datos disponibles para mostrar",
                           url: "//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json",
                        },
                        ordering: false,
                     });
                     $("#DatosEvento").modal({ backdrop: "static", keyboard: false });
                  }

I cannot get de value stored in stock_data. Just one character.

enter image description here

enter image description here

I need get the values stored in stock_data variable and show it in datatable

Prompt : Entered text not showing in terminal

Index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iChat - Realtime Node Socket.io Chat App</title>
    <script src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script src="js/client.js"></script>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <nav>
        <img class="logo" src="chat-removebg-preview (1).png">
    </nav>
    <div class="container">
        <div class="message right">Jack : Hi Peter </div>
        <div class="message left"> Peter : Hi Jack ! how are you ?</div>

    </div>
    <div class="send">
        <form action="#" id="send-container">
            <input type="text" name="messageInp" id="messageInp">
            <button class="btn" type="submit">Send</button>
        </form>
    </div>
</body>

</html>

index.js

const { Socket } = require('socket.io');

Node server which will handle socket io connections
const io = require('socket.io')(8000)

const users = {};

io.on('connection', Socket => {
socket.on('new-user-joined', Name => {
console.log("New user", Name)
users[socket.id] = Name;
socket.broadcast.emit('user-joined', Name)
    });

socket.on('send', message => {
socket.broadcast.emit('receive', { message: message, Name: users[socket.id] })
    });
})

client.js

const socket = io('https://localhost:8000');

const form = document.getElementById('send-container');
const messageInput = document.getElementById('messageInp')
const messageContainer = document.querySelector(".container")

const Name = prompt("Enter your name to join")
socket.emit('new-user-joined', Name)

I was making a chat website from a tutorial then i typed this this :

const Name = prompt ("Enter your name to join") 
socket.emit ('new-user-joined', Name)

I was expecting that I would type the name of anything in the prompt area on website and it will show in terminal but it showed nothing in terminal when i typed and i refreshed many times and used nodemon also to make sure my code was updated

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) in a file where it doesn’t exist and shouldn’t be error

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)showed in console but it’s kind of true,because this event doesn’t exist in my contact.html. It’s different page to index.html where this event works fine.

Seems like webpack is seeing both .html files the same way. The same webpack.config and dependencies work well in other project. I don’t see where is mistake.

 <div class="button img-next">
   <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M20 0H0v20h20zM7.658 15.707l-1.414-1.414L10.537 10 6.244 5.707l1.414-1.414L13.365 10z"/></svg>
  </div>

this is index.html and contact.html doesn’t have this button.
Error shows when I go to contact.html page

this:

 next.addEventListener('click', () => {
    if (auto) {
      clearInterval(imagesInterval);
      imagesInterval = setInterval(nextImg, intervalTime);
    }
    nextImg();
  });

and other
prev.addEventListener() causing chaos

Cannot set breakpoint in chrome dev tools on executable lines

I cannot set a breakpoint on executable lines in chrome dev tools as shown in the photo below.

I should be able to set breakpoints on lines 75 and 78 but I cannot.

I tried stopping the server, rerunning yarn install, and even deleting node_modules and restarting again.

I also tried adding code and saving but it did not fix the issue.

The browser refreshes for changes and loads the new code but still does not allow for breakpoints.

When I run the code it skips those lines, despite them being in the sourcemap.

So it’s not registering the changes.

I tried clearing the browser history, cache, and resetting chrome dev tools with no success.

cannot set breakpoint on executable lines in chrome dev tools

How to send OTP to mobile using Laravel and Firebase

I am trying to implement phone verification in my laravel project using Firebase signInWithPhoneNumber function. I had some problems at first but I managed to put everything together, but now this error is thrown when trying to call signInWithPhoneNumber:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'verify')
    at _verifyPhoneNumber (phone.ts:190:33)
    at signInWithPhoneNumber (phone.ts:190)

I am actually not good at js so I can’t try to debug this error, I tried searching but cou’dn’t find an answer. I found a similar issue on github.

My code:

import {
        initializeApp
    } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js'

    import {
        getAuth,
        signInWithPhoneNumber,
        RecaptchaVerifier
    } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js'

    const firebaseConfig = {
        apiKey: "xxxxxxxxxx",
        authDomain: "xxxxxxxxxxxxx",
        projectId: "puxxxxxxxxxxxxx",
        storageBucket: "pxxxxxxxxxxxxxxxxxxx",
        messagingSenderId: "xxxxxxxxxxxxxx",
        appId: "1:434692xxxxxxxxxxxxxxxxxx168c8757df",
        measurementId: "G-xxxxxxxxxxxxxxxxxx"
    };
    const app = initializeApp(firebaseConfig)
    const auth = getAuth()

    window.onload = function() {
        render();
    };

    function render() {
        window.recaptchaVerifier = new RecaptchaVerifier(auth, 'recaptcha-container', {
            'size': 'normal',
            'callback': (response) => {
                // reCAPTCHA solved, allow signInWithPhoneNumber.
                // ...
                console.log(response)
            },
            'expired-callback': () => {
                // Response expired. Ask user to solve reCAPTCHA again.
                // ...
            }
        });
        window.recaptchaVerifier.render();
    }

    $('#send-code').on('click', function(e) {
        e.preventDefault()
        SendCode()
    })

    function SendCode() {
        var number = $("#phone").val();


        signInWithPhoneNumber(number, window.recaptchaVerifier).then(function(confirmationResult) {

            window.confirmationResult = confirmationResult;
            coderesult = confirmationResult;

            console.log('success')

        });

    }

can someone tell me what am I doing wrong?