0

I was trying to write JS code to highlight element when user hovers a cursor over it. To achieve it I am trying to add eventListener on every children on first tag "nav" in current document:

let navigation = document.getElementsByTagName("nav");
elements = navigation[0].children;

for (element in elements) {
  elements[element].addEventListener("mouseenter", function(event) {
    event.target.style.color = "#ffbf00";
    event.target.style.textShadow = "0px 0px 20px #ffbf00";
    setTimeout(function() {
      event.target.style.color = "";
      event.target.style.textShadow = "0 0 5px #a50068";
    }, 500);
  }, false);
}

But when I open it in browser, not only it does not work, but also Chrome says in DevTools that variable "navigation" is undefined. What am I doing wrong?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Leonid
  • 11
  • 2
    Are you making sure your script only executes once the DOM is fully parsed? Show where and how you integrate the JS into your HTML. – connexo Dec 01 '21 at 21:05
  • 2
    A couple hints: You can get the first element by using `querySelector` so you don't have to specify index zero. Of course, you could chain them and avoid `navigation` altogether: `const navChildren = document.querySelector("nav").children;` Also, you're initializing `elements` as a global variable. – isherwood Dec 01 '21 at 21:05
  • 2
    Why don't you use the `:hover` pseudo class? – lupz Dec 01 '21 at 21:07
  • Please provide **feedback** on comments and answers given! Also try to **answer** questions asked with regard to your question. – connexo Dec 01 '21 at 23:57
  • `elements[element]` must be just `element` and the loop must be `for...of`, not `for...in`. – connexo Dec 01 '21 at 23:59

1 Answers1

0

This can be more easily accomplished using CSS:

nav>*:hover {
  color: #ffbf00;
  text-shadow: 0px 0px 20px #ffbf00;
}

As for your JS:

  • add type="module" or defer attribute to your <script> tags or your DOM won't be loaded when the script is executed and it won't find your nav element.
  • you should loop over the items using for (const element of elements) (instead of in).
connexo
  • 53,704
  • 14
  • 91
  • 128
Okku
  • 7,468
  • 4
  • 30
  • 43