JakeTheSnake
JakeTheSnake

Reputation: 2464

Javascript - Multi-Usage of General Function

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>

Upvotes: 0

Views: 43

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92334

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>

Upvotes: 1

Dola
Dola

Reputation: 1483

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>

Upvotes: 2

Related Questions