Albin Lang Albin Lang - 1 year ago 85
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:

function myFunction() {
document.getElementById("myIdHere").style.backgroundColor = "red";

...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 Source

You could make an object that has everything self contained. Here is a working example:


<div id="first">
  click 1

<div id="second">
  click 2


var colorSwapper = function(id) {

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

  this.swapColor = function() { = 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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download