0

I have a example of a situation here, I want to change the color of a div when clicked. Do I have to have two different functions, one for each div? What if the functions that I wanted to apply to the div was very complex? What if I had hundereds of the div? Can I make a general function, that can be applied for every div? By this I do not mean for example document.getElementsByClassName(" ... "), I want to for example change the color of the separately.

To be clear, how can I apply the same function to different objects? Something like document.getElementThatIsClicked(" ... " ) Thank you.

function changeColor1() {
  document.getElementById("div1").style.backgroundColor = "#21a9c9";
}
function changeColor2() {
  document.getElementById("div2").style.backgroundColor = "#21a9c9";  
}
<div id="div1" onClick="changeColor1()" style="position:absolute; top:10px; left: 10px; width:200px; height: 200px; background-color:#000000;"></div>
                      
<div id="div2" onClick="changeColor2()" style="position:absolute; top: 10px; left: 220px; width:200px; height: 200px; background-color:#000000;"></div>
JakeTheSnake
  • 2,456
  • 3
  • 14
  • 26

2 Answers2

2

You can make a function that accepts the element you want to change the color and make the function change the background color for that element

 function changeColor(elem) {
   elem.style.backgroundColor = "#21a9c9"
 }
<div id="div1" onClick="changeColor(this)" style="position:absolute; top:10px; left: 10px; width:200px; height: 200px; background-color:#000000;"></div>

<div id="div2" onClick="changeColor(this)" style="position:absolute; top: 10px; left: 220px; width:200px; height: 200px; background-color:#000000;"></div>
Dola
  • 1,483
  • 11
  • 16
  • 2
    I was just typing the exact same thing ;) – DRGA Sep 28 '15 at 17:36
  • Ok, so I use `function(this)` in the `onClick` and `elem` in the function declaration? Thank you. – JakeTheSnake Sep 28 '15 at 17:39
  • 2
    Please don't suggest HTML attribute handlers – Ruan Mendes Sep 28 '15 at 17:45
  • @JakeTheSnake, Yes, when do an inline function call (which is calling the javascript function inside onclick attribute in the html tag), you can pass 'this' keyword as a parameter to be able to access the element which had the event. then inside the function you will have access to that element and would be able to modify it or do whatever you want with it – Dola Sep 28 '15 at 17:45
1

Copied from https://stackoverflow.com/a/32828729/227299 but:

function changeColor(elem) {
  elem.style.backgroundColor = "#21a9c9"
}


var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', function(e) {
    changeColor(this);
  });
}
#div1,#div2 {
  display: inline-block;
  width: 200px; 
  height: 200px; 
  background-color:#000000;
}
<div id="div1"></div>

<div id="div2"></div>
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217