nastan
nastan

Reputation: 55

several eventhandler in one function

Instead of creating a new function for every button handler i wanna create just one function and handle all the buttons there.I wanna the first button to do something different than the second one....My idea was to have one eventlistener but how do i know the target.id is the same as btn1 for example?

<div class="col-11" id="btns">
         <button class="btn btn-dark" id="btn1">Button 1</button>
         <button class="btn btn-dark" id="btn2">Button 2</button>
         <button class="btn btn-red" id="btn3">Button 3</button>
         <button class="btn btn-blue" id="btn4">Button 4</button>
</div>


let btn1=document.getElementById('btns');
btn1.addEventListener("click",doStuff);

function doStuff(e){
if(e.target.id===document.getElementById('btn1')){   //doesnt work
   console.log("Hello");
   }else if(e.target.id===.getElementbyId('btn2'){
      //doSomething...
       }
}

Upvotes: 1

Views: 36

Answers (1)

RobertAKARobin
RobertAKARobin

Reputation: 4274

You have the right approach, there's just an error in your code:

e.target.id===document.getElementById('btn1')

This compares the ID of the element that was clicked to the element with the ID of 'btn1'.

That is, it compares a string to an element.

Naturally, this will always return false.

Instead, try:

e.target===document.getElementById('btn1')

This compares an element to an element.

Or:

e.target.id==='btn1'

This compares a string to a string.

Optional: You could simplify your code by using a switch/case block instead of a bunch of if statements. Here's how I would write your click handler:

function doStuff(e) {
    switch(e.target.id){
        case 'btn1':
            // Do something for btn1...
            break;
        case 'btn2':
            // Do something for btn2...
            break;
    }
}

More information about switch/case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Upvotes: 2

Related Questions