Albin Lang Albin Lang - 3 months ago 15
Javascript Question

Javascript clickable multiple times with different results

I'm using this code to change the background color of a div when clicking it:

<script>
function myFunction() {
document.getElementById("myIdHere").style.backgroundColor = "red";
}
</script>


...this works fine but I'd like for it to change to another color if I click on it again if possible.

Also I'd like to apply this function to multiple div's. They should all change color when I click on them not depending on each other. Is there a good way to do this or do I have to assign each div a unique Id and create multiple functions? I've tried using the getElementByClass but that did'nt solve my problem.

Thank you!

Answer

You could make an object that has everything self contained. Here is a working example: https://jsfiddle.net/avzoqroa/

HTML:

<div id="first">
  click 1
</div>

<div id="second">
  click 2
</div>

Javascript:

var colorSwapper = function(id) {

  this.element = document.getElementById(id);
  this.position = 0;
  this.colors = ["red", "purple", "blue"];

  this.swapColor = function() {
    this.element.style.backgroundColor = this.colors[this.position];
    this.position = (this.position + 1) % this.colors.length;
  }

    //bind event listener for click
  this.element.addEventListener("click", this.swapColor.bind(this));
}

var colorSwapper1 = new colorSwapper("first");
var colorSwapper2 = new colorSwapper("second");