0

Have a quick question that I think is relatively simple, I'm just missing something. I have a navbar that when the menu items are hovered, I want to append a class of "open" to them". I'm using the following code:

function setNavItemToOpen(navItem){
    navItem.classList.add('open');
}

    document.addEventListener("DOMContentLoaded", function(){
    var primaryNavMenuItems = document.getElementsByClassName('primarynav__menuitem');
    for(var i = 0; i < primaryNavMenuItems.length; i++) {
        primaryNavMenuItems[i].addEventListener("mouseenter",  function(){
            setNavItemToOpen(primaryNavMenuItems[i]);    
        });
    };});

The console is telling me that "navItem" is undefined in the function. Is my code for adding the event listener not correct?

JesseEarley
  • 1,036
  • 9
  • 20
  • 1
    `primaryNavMenuItems[i].onmouseenter = setNavItemToOpen` then inside the function you can use `this.classList.add(...)` – Calvin Nunes Sep 19 '19 at 19:43
  • 4
    `var i` is your problem. Change it to `let i` – Patrick Roberts Sep 19 '19 at 19:43
  • In setNavItemToOpen? – CoderCharmander Sep 19 '19 at 19:43
  • @PatrickRoberts, that was it, thank you! I've been staring at this for about 30 minutes and didn't catch that! I need a break. – JesseEarley Sep 19 '19 at 19:45
  • There's a very good duplicate out there with extensive explanation around this topic, but as usual I can't find it because the Stackoverflow duplicate search is so incredibly terrible. – Pointy Sep 19 '19 at 19:46
  • @Pointy I did a search prior but couldn't find anything. – JesseEarley Sep 19 '19 at 19:49
  • 1
    @PatrickRoberts I just find it extremely frustrating in general, there doesn't seem (to me) to be any predictability as to how to get it to find questions that I *know* exist – Pointy Sep 19 '19 at 19:49
  • 1
    @Pointy sorry, I meant, do the duplicates I selected contain the one you were referring to or no? – Patrick Roberts Sep 19 '19 at 19:49
  • @PatrickRoberts like, I searched for "Javascript loop simple" and it did not turn up that question, which of course was exactly what I was looking for. The search results are not even sorted by upvote! It's really weird how bad it is. – Pointy Sep 19 '19 at 19:50
  • @PatrickRoberts no your dup is the right one, I'm not mad at you personally :) :( – Pointy Sep 19 '19 at 19:51
  • 1
    My secret is I use [google searches](https://www.google.com/search?q=site:stackoverflow.com+Javascript+loop+simple) with `site:stackoverflow.com`. The keyword matching performs much better from Google than from Stack Overflow. – Patrick Roberts Sep 19 '19 at 19:51

0 Answers0