Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Monday, January 18, 2016

Change CSS color with Javascript on click (addEventListener)

Answer by Gautam Jha for Change CSS color with Javascript on click (addEventListener)


try this..

$('#box1').click(function(){      $('.border #box1').css('background-color', 'red').css('color', 'red');  });
     

Answer by Praveen Kumar for Change CSS color with Javascript on click (addEventListener)


I believe you should give the function reference and not execute the function there:

document.getElementById("box1").addEventListener("click", click1);  //-------------------------------------------------------------^  

Do not "call" the function there.

Answer by Dhaval Patel for Change CSS color with Javascript on click (addEventListener)


You just need to add click event in HTML

and remove document.getElementById("box1").addEventListener("click", click1(1));

Answer by Suresh Ponnukalai for Change CSS color with Javascript on click (addEventListener)


If you want to pass arguments in addEventListener, you have to modified your code like below.

 document.getElementById("box1").addEventListener("click", function(){click1(1);}, false);  

DEMO

Answer by Werner for Change CSS color with Javascript on click (addEventListener)


As others already mentioned there is an issue in your second addEventListener parameter.

You may look at this example:

var colorcheck = "#cccccc";    function click1() {    document.getElementById(this.id).style.backgroundColor = '#ff0000';    colorcheck = document.getElementById("box1").style.backgroundColor;    console.log(colorcheck);    console.log(this.id);  };    document.getElementById("box1").addEventListener("click", click1);

PS: look at the style attribute of box1. It's background-color not backgroundColor. The second one is only for JavaScript.

Answer by Rajesh for Change CSS color with Javascript on click (addEventListener)


As I have commented, document.getElementById("box1").addEventListener("click", click1(1)) was issue. Also instead of passing numbers click1(1), you can use this.

You can try something like this:

Code

var colorcheck = "#cccccc";    function click1(blockid) {    var self = this;    self.style.backgroundColor = '#ff0000';    colorcheck = self.style.backgroundColor;    console.log(colorcheck);    console.log("box" + blockid);  };      function registerEvents(){    var box = document.getElementsByClassName("box");    for(var i = 0; i
.box {    width: 100px;    height: 100px;    background: black;    margin:5px;  }
    

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.