0

I have a set of 3 menu items that i'm trying to add a mouseenter event to. I can't seem to get it to work at all. I've also tried looping through the .menu-item class and nothing is happening.

It's driving me nuts. Does anyone know why this isn't working?

Many thanks in advance for any help

Code is below and Codepen link is: https://codepen.io/emilychews/pen/VzaOoe

(Also I can't have a jQuery solution).

JS

var menuItem = document.querySelectorAll('.menu-item');

  function myMouseEnter() {

    alert('mouse entered');

  }

menuItem.addEventListener('mouseenter', myMouseEnter, false)

Commented-Out Version Using a Loop

//   function myMouseEnter() {

//     for(i=0; i < menuItem.length; i++){

//        alert ('mouse entered');
//       
//       }

//     }

//   menuItem.addEventListener('mouseenter', myMouseEnter, false)

CSS

.menu-item {
padding: 10px;
font-family: arial;
}

HTML

<ul class="unclick--menuitems">
  <li class="menu-item item1"><a href="//google.com">About</a></li>
  <li class="menu-item item2"><a href="//google.com">Work</a></li>
  <li class="menu-item item3"><a href="//google.com">Contact</a></li>
</ul>
pjk_ok
  • 618
  • 7
  • 35
  • 90
  • 3
    `menuItem` is a `HTMLCollection`, so to add listeners you need to iterate through it and add listener to each element from the collection – MysterX Aug 01 '17 at 14:00
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Teemu Aug 01 '17 at 14:11

2 Answers2

1

You have to iterate throw the collection and add event listener on each element like this :

var menuItems = document.querySelectorAll('.menu-item');

function myMouseEnter() {
 alert('mouse entered');
}

for(var i=0; i < menuItems.length; i++) {
  menuItems[i].addEventListener('mouseenter', myMouseEnter, false);
}
Yordan Nikolov
  • 2,598
  • 13
  • 16
0

JS query selectors will always return the element in the form of array, so in your case you can use something like this,

var menuItems = document.querySelectorAll('.menu-item');

function myMouseEnter() {
 console.log('mouse entered');
}

menuItems[0].addEventListener('mouseenter', myMouseEnter);
Saravanan I
  • 1,229
  • 6
  • 9
  • It is not an array but an HTMLCollection. The big difference is that some array methods (like forEach) won't work on it. – lumio Aug 01 '17 at 17:51