By Jan Lasota


2018-07-12 00:00:47 8 Comments

I'm trying to apply a hover effect to a grid, so when my mouse passes over the container, a certain grid square will turn black. However, when I mouse over the grid, the entire grid turns black. I have come to realize that when there is more than one element with the same class name, it will change the color of all of them.

var hoverContainer = document.getElementById('container');
hoverContainer.addEventListener('mouseover', function(e) {
  var colorChange = document.getElementsByClassName('grid-item');
  for(var i = 0; i < colorChange.length; i++){
    colorChange[i].classList.add('hoverColor');
    console.log(e);
  }
});

I would love a push in the right direction! Thanks!

1 comments

@CertainPerformance 2018-07-12 00:06:23

Try finding the closest .grid-item to the target and changing its classList:

var hoverContainer = document.getElementById('container');
hoverContainer.addEventListener('mouseover', function(e) {
  const gridItem = e.target.closest('.grid-item');
  if (gridItem) gridItem.classList.add('hoverColor');
});
.grid-item {
  border: 1px solid black;
}
.hoverColor {
  background-color: yellow;
}
<div id="container">
  <div class="grid-item">item</div>
  <div class="grid-item">item</div>
  <div class="grid-item">item</div>
  <div class="grid-item">item</div>
</div>
  

(you'll also need to remove the hoverColor after the mouse leaves the .grid-item)

But this would be more easily achieved with CSS alone, with :hover:

.grid-item {
  border: 1px solid black;
}
.grid-item:hover {
  background-color: yellow;
}
<div id="container">
  <div class="grid-item">item</div>
  <div class="grid-item">item</div>
  <div class="grid-item">item</div>
  <div class="grid-item">item</div>
</div>

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

26 Answered Questions

65 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 4776497 View
  • 6007 Score
  • 65 Answer
  • Tags:   javascript arrays

49 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

88 Answered Questions

[SOLVED] How do JavaScript closures work?

52 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

34 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

48 Answered Questions

30 Answered Questions

[SOLVED] Change an element's class with JavaScript

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2112044 View
  • 2267 Score
  • 30 Answer
  • Tags:   javascript html dom

Sponsored Content