Search code examples
javascriptfor-loopmenuonmouseoveronmouseout

onmouseover for menu created with foor loop


I have created one simple menu using for loop in javascript because the most elements are the same for every 'tab', so I did it all in one go using the for loop.

My question is how can I use onmouseover event to change the tab's background color when I hover on it using mouse.

Example:

TopValues = [ "130px", "163px", "196px" ];
MenuNames = [ "Home", "Articles", "Contact" ];
MenuItemLinks = [ "#", "#", "#" ];
MenuItemTitles = [ "Go To Home", "Go To Articles", "Go To Contact" ];

window.onload = function makeMenu() {
    for(var i=0; i<MenuNames.length; i++) {
        var menu = document.createElement('a');
        menu.text = MenuNames[i];
        menu.title = MenuItemTitles[i];
        menu.href = MenuItemLinks[i];
        document.body.appendChild(menu);

        menu.style.position = "fixed";
        menu.style.border = "1px solid red";
        menu.style.width = "90px";
        menu.style.top = TopValues[i];
        menu.style.left = "5px";
        menu.style.padding = "5px";
        menu.style.borderRadius = "5px";
        menu.style.textDecoration = "none";
        menu.style.background = "yellow";
        menu.style.color = "red";

    }
    menu.onmouseover = function() { menu.style.background = "orange"; };
    menu.onmouseout = function() { menu.style.background = "yellow"; };
}

In this example, only the last tab changes the background color as it should. Can you help me to understand how I'm supposed to do it.

I was thinking to make an empty array and assign to every tab it's id, and using another for loop and if statements to determine which tab is it, and change it's color, but I didn't manage.

Thanks everyone


Solution

  • Move event listener inside loop.

     for(var i=0; i<MenuNames.length; i++) {
            var menu = document.createElement('a');
            menu.text = MenuNames[i];
            menu.title = MenuItemTitles[i];
            menu.href = MenuItemLinks[i];
            document.body.appendChild(menu);
    
            menu.style.position = "fixed";
            menu.style.border = "1px solid red";
            menu.style.width = "90px";
            menu.style.top = TopValues[i];
            menu.style.left = "5px";
            menu.style.padding = "5px";
            menu.style.borderRadius = "5px";
            menu.style.textDecoration = "none";
            menu.style.background = "yellow";
            menu.style.color = "red";
            (function(el) {
                el.onmouseover = function() { el.style.background = "orange"; };
                el.onmouseout = function() { el.style.background = "yellow"; }
            }(menu));
        }