Search code examples
javascriptaddeventlistenerevent-listener

Can I have an EventListener that responds to a certain numeric value?


In this web app I'm building to keep score in some game, I'm trying to change the background color of a certain element when your score reaches 6000 points or more. It should respond to an <input> element of type = 'number'. I think I'm on the right track but so far I can't get it to work (and I'm not 100% sure that onchange is the right event type).

Here is the code I got now.

In the html-file:

<input type="number" id="scorePlayer1" value=0 readonly="true">

In JS:

const scorePlayer1 = document.querySelector("#scorePlayer1");
const scoreBackGrPlayer1 = document.querySelector(".scoreBord #scorePlayer1");


scorePlayer1.addEventListener('change', () => {
    const currentScorePlayer1 = scorePlayer1.value;
    if (currentScorePlayer1 >= 6000) {
        scoreBackGrPlayer1.style.backgroundColor = ("gold");
    };
})

Thanks in advance for your help!

UPDATE: here is a reprex of my current code:

  <input type="number" id="scorePlayer1" value=0 readonly="true">
  <button id="addButton">+ 1000</button>
const addButton = document.querySelector("#addButton");
const scorePlayer1 = document.querySelector("#scorePlayer1");

// Adding 1000 points
addButton.addEventListener('click', () => {
    scorePlayer1.value = +scorePlayer1.value + 1000;
    handleValueChange(scorePlayer1.value);
});

// Change color on points >= 6000
scorePlayer1.addEventListener('input', (e) => {
    const currentScorePlayer1 = e.target.value;
    if (currentScorePlayer1 >= 6000) {
        scorePlayer1.style.backgroundColor = ("gold");
    };
})

Solution

  • Programatically changing the input value won't trigger the input event (or the 'change' event which actually only fires when the input loses focus). You can trigger the event manually (see: Trigger Change event when the Input value changed programmatically?)

    But it is much more direct to handle the side effect in the handler itself.

    const addButton = document.querySelector("#addButton");
    const scorePlayer1 = document.querySelector("#scorePlayer1");
    
    addButton.addEventListener('click', () => {
        let currentScorePlayer1 = scorePlayer1.valueAsNumber;
        let updatedScorePlayer1 = currentScorePlayer1 + 1000;
        
        scorePlayer1.value = updatedScorePlayer1;
        
        if (updatedScorePlayer1 >= 6000) {
            scorePlayer1.style.backgroundColor = ("gold");
        };
        
        //handleValueChange(scorePlayer1.value);
    });
    <input type="number" id="scorePlayer1" value=0 readonly="true">
    
    <button id="addButton">+ 1000</button>