I have a bunch of WordPress posts being spit out in a 2x8 grid. I gave them all class of post. I have the following code my goal is to get the div.post that I hover over a color that changes everytime I hover over it (or another post).
var colors = ['rgba(0, 163, 235, 0.7)', 'rgba(209, 28, 9, 0.7)', 'rgba(255, 232, 45, 0.9)', 'rgba(136, 18, 6, 0.7)', 'rgba(0, 110, 159, 0.7)', 'rgba(224, 199, 0, 0.9)']
var i = 0;
var element = document.getElementsByClassName('post');
element.onmouseover = function() {
console.log("Hello");
var color = colors[i]
this.style.backgroundColor = color;
}
element.onmouseout = function() {
this.style.backgroundColor = "transparent";
if (i >= 5) {
i = 0;
}
else {
i++;
}
}
When I do getElementById I can get the first one to work but none of the others (probably because I shouldn't have the same ID on a page multiple times so I took that out of my loop)
PS I need an answer with no jQuery please. (I already know this is easier with jQuery and have a solution in jQuery but I have been tasked to not use it)
@nnnnnn got me my answer by pointing me to a similar question for anyone curious this is my working code.
var element = document.getElementsByClassName('post');
for (var i = 0; i < element.length; i++) {
element[i].onmouseover = function() {
console.log("Hello");
var color = colors[j]
this.style.backgroundColor = color;
}
element[i].onmouseout = function() {
this.style.backgroundColor = "transparent";
if (j >= 5) {
j = 0;
}
else {
j++;
}
}
}