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>
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");