Vlad
Vlad

Reputation: 33

addEventListener and if statement on button clicked

I am new to coding and here I am trying to use addEventListener and if statement to change the color of the box when button clicked, but I am not doing it the right way and not managing to find the proper way online.

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no  = document.getElementById("no");
yes.addEventListener("click", function(){
    if (yes.clicked == true){
        box.style.backgroundColor = "red";        
    } if(no.clicked == true) {
        box.style.backgroundColor = "green";
    }
});

Upvotes: 0

Views: 15126

Answers (3)

George Carlin
George Carlin

Reputation: 447

function colorChange(e) {
    if(e.target.id == 'yes'){ // if user clicked the yes button
        box.style.backgroundColor = "red";

    }else if(e.target.id == 'no'){ // if user clicked the no button
        box.style.backgroundColor = "green";
    }
}
yes.addEventListener('click', colorChange);
no.addEventListener('click', colorChange);

Upvotes: -1

Layer
Layer

Reputation: 336

You are only aplying a listener to the button yes, so your listener only will works for your yes button:

//Listener attached only to yes
yes.addEventListener("click", function(){
    if (yes.clicked == true){
        box.style.backgroundColor = "red";        
    } if(no.clicked == true) {
        box.style.backgroundColor = "green";
    }
});

So you don't need an if statement for your purpose, you only need various listeners:

box.addEventListener("click", function(){
     alert("box clicked!");
});

yes.addEventListener("click", function(){
     box.style.backgroundColor = "red";
)};

no.addEventListener("click", function(){
     box.style.backgroundColor = "green";
});

And if your buttons are inside the box you can do this instead of the upper functionality:

box.addEventListener("click", function(ev){

    if(ev.currentTarget.id == "yes"){
        box.style.backgroundColor = "red";
    }else if(ev.currentTarget.id == "no"){
        box.style.backgroundColor = "green";
    }

});

Upvotes: 1

Aplet123
Aplet123

Reputation: 35512

When you add an event listener to the yes button, it will only trigger when the yes button is clicked. Therefore, you need a separate one for both buttons and no if statement is necessary.

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no  = document.getElementById("no");
yes.addEventListener("click", function(){
        box.style.backgroundColor = "green";        
});
no.addEventListener("click", function(){
        box.style.backgroundColor = "red";        
});

Upvotes: 0

Related Questions