Search code examples
javascriptbookmarklet

How can I apply a event listener to an array of elements?


So I am trying to make a bookmarklet that when you hover over things, they light up, and this is what I have so far

var h1 = document.getElementsByTagName("h1");
h1length = h1.length;
for (var i=0; i <= h1.length; i++) 
{
    h1[i].addEventListener("mouseover", lightUp, false);
}
function lightUp()
{
    h1[i].style.textShadow = "2px 2px 5px blue";
}

But this just doesn't do anything when I hover over the h1 element that I am using, can someone tell me what I am doing wrong if I add a () after the lightUp, it immediately runs the function without me hovering over. Also, there is nothing wrong with the for loop, when I applied the text shadow without the hovering, it applied it to all h1 elements, it is something wrong with the listener I think.


Solution

  • I highly recommend switching from index-based looping to for...of instead, which is much more readable:

    const headlines = document.getElementsByTagName("h1");
    for (const headline of headlines) {
        headline.addEventListener("mouseover", lightUp, false);
    }
    
    function lightUp(event) {
      event.target.style.textShadow = "2px 2px 5px blue";
    }
    <h1>Foo</h1>
    <h1>Bar</h1>
    <h1>Baz</h1>