Remove Last Character in th using ajax

how to remove last character inside of table header using javascript/ajax?

Example table

Product Price X
First 1000
Second 2000

what i want to reach is remove the X on Price X column header with some button, I’ve use slice before but not working.

how i supposed to do?

Thanks

how to avoid recursion or to fix the problem?

Teaching JS trying to do a ticatactoe game and got a problem with recursion, specifically with ‘Maximum call stack size exceeded’.

When I try to make a random move by the computer player I make a random number, which then will be checked of his value in array called gameState.
So, if this value has defined already (there are X or O mark in a cell), I need to generate a random number again. So I need to stop this infinite loop when all cells are marked or I’ll get an error ‘Maximum call stack size exceeded’.

Can you please take a look, am I do the right thing or it is generally wrong?
Actually, I thought about another implementation of this game scene, but I thought if i’ve started with that I should lead this to the end


let gameState = ["", "", "", "", "", "", "", "", "",];
let playerAi = "O";

// ai's turn
function playerAiTurn() {
    let randomNum = Math.floor(Math.random() * gameState.length);
    if (gameState[randomNum] === '') {
    gameState[randomNum] = playerAi;
    document.getElementById(randomNum).innerHTML = playerAi;
    resultCheck();
    } else {
        playerAiTurn()
    };
};

catch in promise not working in javascript

Any ideas why my .catch won’t work whenever I provide a wrong number (“articlenumber” that doesn’t exist)?

fetch(`/scripts/articles/${articlenumber}.txt`)
    .then(response => response.text())
    .then(responsearticle => articlecontent.innerHTML = responsearticle)
    .catch(function() {
        console.log("File not found")
});

How to modify & replace the key an object by comparing it with other objects?

I have an array of object which consists some id’s as a key.

const sampleObj1 = {0011:[{},{}], 0022:[{}, {}], 0033:[{},{}]}
const sampleObj2 = {{id:0011, name:test1}, {id:0022, name:test2}, {id:0033, name:test3}}

I want to compare sampleObj1 key with the sampleObj2 id value and then need to create new obj some like below.

const newObjByComparing = {test1:[{},{}], test2:[{},{}], test3:[{},{}]} //desired result 

I have tried using for loop but not able to get the desired compared value.

const fromRdx = sampleObj2; 
const fromApi = sampleObj1; 
const keys = Object.keys(fromApi);
const newObjAfterComparision = {};

for (let i in fromRdx) {
    newObjAfterComparision[fromRdx[i]] = fromApi[keys[i]];
    fromApi[fromRdx[i]] = fromApi[keys[i]];
    delete fromApi[keys[i]];
}

console.log(newObjAfterComparision)

Website -> Count Button Clicks and never reset

Holaaa

I wanted to create a simple website containing a button. If I press the button 5 times, it says 5. When I refresh the page, it should still say 5.
And when You load the page, it also says 5 and you can go on clicking.

I know how to build a counter for ONE session and one user, but I have nooo idea how to implement it to be stored “online”.
I am a beginner -> do you guys have any ideas on how to go on?

Javascrypt “Image.onload” fires even if the image is not found

I am trying to load some image for a HTML canvas game. And I want them to load before I start the game. So I created a function to load them synchronously before my game starts. But the problem is,

if the image does not exists, it still fires “Image.onload()”.

I want to return an object with “error=true” if the image doesn’t exist.
But couldn’t find a way.

Here is the function I wrote:

function loadImages(images) {
    return {
        list: images,
        loaded: {},
        failed: {},
        _load(src, name){
            return new Promise((resolve)=>{
                let image = new Image()
                image.onload = resolve({ name, src, image, error: false })
                image.onerror = resolve({ name, src, image: null, error: true })
                image.src = src
            })
        }
    }
}

let myLoader = loadImages("some image list")
let image = await myLoader._load("https://someUrl.com/img.png", "imageName")

console.log(image)

if you look at the console you’ll see the “onload” gets fired not “onerror”.

Digital business card generator [closed]

I just need to know how to generate a digital business card. I need to add that function to my project. I use PHP and JS. I only need to add a name, contact number, and email to that business card. actually, I have no idea how to do that. can someone help me to do that? it’s my university project. Thanks in advance.

Regards,
Samitha.

Why isn’t doc.data() a function in this if-statement?

When I remove the if-stament I get the data and doc.data() works, but I need to check for type ‘added’ so I don’t output existing data again and again.

With the if-statement, I get this error message:

Uncaught TypeError: doc.data is not a function

 async getChats(callback){
    const roomFilter = query(colRef, where("room", "==", this.room));
    const ordered = query(roomFilter, orderBy('created_at'));
    this.unsub = onSnapshot(ordered, (snapshot) => {
      let items = []
      snapshot.docChanges().forEach(doc => {
        if(doc.type === 'added'){
          items.push({ ...doc.data(), id: doc.id })
          console.log(items);
          callback(items);
      }})    
    });

Converting custom Leafet cluster from Vanilla Js code into React Js code

I’m trying to convert this code http://bl.ocks.org/gisminister/10001728 from Vanilla Js into React Js code. The code is about creating a custom UI for Leaflet clustering using a Pie Chart.

Here is the target.
enter image description here

Problem

I have copied and pasted the code from the blog but the cluster didn’t show as seen in the image below.
enter image description here

Code

Playground: https://codesandbox.io/s/learn-react-leaflet-cnk8tm?file=/src/components/CustomCluster/index.jsx

Steps to Reproduce

  1. Open and run the playground.
  2. Make sure you open the Custom Cluster page by adding /4 to the URL for example https://cnk8tm.csb.app/4 in the playground as seen in the image below.
    enter image description here

Question

I’m not familiar enough with Vanilla Js but I’m familiar enough with React Js.
So what’s wrong with my converted code (in the playground) and what’s the correct one?

Note

Actually, I have already created a custom Leaflet clustering in React Js using leaflet, react-leaflet, and react-leaflet-markercluster libraries here but still had a problem.

NS Error not initialized after capturing html canvas

I’m trying to record a svg animation using javascript/html. This is what i’ve tried so far:

<canvas id="canv">
    <svg width="370" height="370" viewBox="0 0 370 370" fill="none" xmlns="http://www.w3.org/2000/svg">
        <!-- my svg is here, full code is below because i don't think it's important -->
    </svg>
</canvas>
<style>
    @keyframes animation{
        from{
            opacity: 0;
            transform: translateY(20%);
        }to{
            opacity: 1;
            transform: translateY(0);
        }
    }
    #bubbles{
        animation: animation 1s linear;
    }
</style>
<script>
const canvas = document.getElementById("canv")

var videoStream = canvas.captureStream(30);
const render = () => {
    videoStream.getVideoTracks()[0].requestFrame();
}
setInterval(render, 33)
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
    chunks.push(e.data);
};
mediaRecorder.onstop = function(e) {
    var blob = new Blob(chunks, { 'type' : 'video/mp4' });
    chunks = [];
    var videoURL = URL.createObjectURL(blob);
    video.src = videoURL;
};

mediaRecorder.start();
setTimeout(() => {
    mediaRecorder.stop();
}, 1000)
</script>

I have got the source code from https://medium.com/@amatewasu/how-to-record-a-canvas-element-d4d0826d3591 and i’m using firefox.
full source: https://paste.gg/p/anonymous/89d475bc50bc469dad827a620d3f7c02

Javascript async await timing

The following code is asynchronous.

async function test_function() {
    await (()=> {
        for(let i = 0; i < 10000000000; i+=1) {
        }
    })();
    console.log('hello 2');
}

test_function();
console.log('hello 1');

Output:

hello 1
hello 2

The function runs asynchronously and so we see hello 1 outputted before hello 2. However, both outputs are printed on the console at the same time rather than hello 2 being printed out a short while after hello 1. The program should execute code written directly after a call to an asynchronous function but that isn’t happening in this case. Why isn’t there a notable pause between the two logs?

What’s the use of callback form of setState given by useState hook?

Question is specifically related to functional components only

[state, setState] = useState(0);
// 1st way to increment by one
setState(state + 1);
// 2nd way to increment by one
setState((prevState) => prevState + 1);

What is the need for the second way? Is there any use case for that can only be met using the 2nd format? Is there any case where state !== prevState inside setState?