0

I've tried to make event deledation, set "click" event on body. Event works on button. But why it doesn't work on body?

window.onload = function(){
var bodyN = document.body,
    bodyS = bodyN.style
bodyS.transition = "all 0s";
bodyS.backgroundColor = localStorage.getItem("bgc")


bodyN.addEventListener("click", function(e){
    console.log(e.target);     // why  doesn't work this when I click on body?
    if (e.target.tagName == "BUTTON") {
        console.log(e);
        bodyS.transition = "";
        bodyS.backgroundColor = e.target.id;
        localStorage.setItem("bgc", e.target.id);
    }
});

};

the same via jQuery:

$(document).ready(function(){
$("body").css("transition", "all 0s" );
$("body").css("backgroundColor", localStorage.getItem("bgc"));

$("body").on("click", "button", function(e){
    console.log(e);
    $("body").css("transition", "" );
    $("body").css("backgroundColor", e.target.id);
    localStorage.setItem("bgc", e.target.id);
}) 

});

1 Answers1

0

With jQuery, I used "click" instead of "on". Here's an example:

$("body").click(function(e){
    console.log(e);
    if(e.target.id == "button"){
        alert('button');
    }
    else{
        alert('body');
    }
});

https://jsfiddle.net/aumayk6s/

Hope it helps you!

Javi Medina
  • 68
  • 1
  • 6