Search code examples
javascriptif-statementclickcounteraddeventlistener

Javascript if else with click dont


i need your help, i'm trying to programm a button that only works if you have 20.

here is my code:

const number = document.getElementById('number')
const button = document.getElementById('button')
const button_two = document.getElementById('button2')

let counter = 0;

button.addEventListener('click', function(){
    counter++
number.innerHTML = counter
})



if(number >= 20){
    button_two.addEventListener('click', function(){
        counter++
        counter++
        number.innerHTML = counter
    })
}else{}

Solution

  • Attach one listener to a parent element (.buttons). Use event delegation to catch events from its child elements as they "bubble up" the DOM. If the child element that fired the event is a button work through the conditions.

    // Cache the elements you'll be using
    const number = document.querySelector('.number');
    const buttons = document.querySelector('.buttons');
    const plusTwo = document.querySelector('#plusTwo');
    
    // Add one listener to the button container
    buttons.addEventListener('click', handleClick);
    
    let counter = 0;
    
    function handleClick(e) {
      
      // If the child element that fired the event
      // is a button
      if (e.target.matches('button')) {
        
        // Destructure its id
        const { id } = e.target;
        
        // Add one, and if the counter is 20
        // enable the `plusTwo` button
        if (id === 'plusOne') {
          ++counter;
          if (counter === 20) plusTwo.disabled = false;
        }
        
        // Add two
        if (id === 'plusTwo') counter += 2;
    
        // Minus one
        if (id === 'minusOne') --counter;
      
      }
      
      // Update the number
      number.textContent = counter;
    
    }
    <section class="buttons">
      <button id="plusOne">Plus one</button>
      <button id="plusTwo" disabled>Plus two</button>
      <button id="minusOne">Minus one</button>
    </section>
    <div class="number"></div>

    Additional documentation