简体   繁体   中英

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";
    }
});

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";
    }

});

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";        
});
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM