1

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++;
    }
  }
}
Parzi
  • 694
  • 2
  • 10
  • 33
  • 3
    Your `element` variable is actually a *list*. You can't assign event handlers to a list, you have to iterate over the list and assign handlers to the individual elements in the list. – nnnnnn Mar 30 '17 at 09:12
  • Ah didn't realize this was returning an array. So I need a for loop to loop through my array adding my onmouseover function to each element inside of the array? – Parzi Mar 30 '17 at 09:15
  • Yep, it returns an array-like object (not an actual array). Even if only one element was found, you'd get back a list with one element in it. Other than the duplicate I linked to, [here](http://stackoverflow.com/questions/13667533/getelementsbyclassname-onclick-issue) is another similar question, or the more generic [What do `getXByY()` methods return question](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method). – nnnnnn Mar 30 '17 at 09:17
  • AWESOME!!! Thank you @nnnnnn that got me my answer. For anyone curious I have updated my question with my working code. :) – Parzi Mar 30 '17 at 09:23

0 Answers0