Search code examples
javascriptfor-loopuncaught-exception

For loop error: Uncaught ReferenceError, variable is not defined. What's wrong?


I've created a css menu, and I want to make each one of them to change their color on mouseover event (I'm just learning javascript, and specially the for loop, I know can achieve this with CSS3).

So, It's not working, I get this error on the DOM console: Uncaught ReferenceError: linkIdOn is not defined (line 44)

This is my CSS:

<body>
<div id="menuPrincipal">
<div id="link1" class="link"><a href="">Link 1</a></div>
<div id="link2" class="link"><a href="">Link 2</a></div>
<div id="link3" class="link"><a href="">Link 3</a></div>
<div id="link4" class="link"><a href="">Link 4</a></div>
</div>

This is my javascript:

    function cambioColorOnMouseover(){
    for (linkId=1; linkId<5; linkId++){
        var linkIdOn='link'+linkId;
        document.getElementById(linkIdOn).style.backgroundColor="#eee";
        console.log(linkIdOn);
    }
}
function cambioColorOnLeave(){
    for (linkId=1; linkId<5; linkId++){
        var linkIdOff='link'+linkId;
        document.getElementById(linkIdOff).style.backgroundColor="#ccc";
        console.log(linkIdOff);
    }
}
document.getElementById('link'+linkIdOn).onmouseover=cambioColorOnMouseover;  <-- line 44
document.getElementById('link'+linkIdOff).onmouseout=cambioColorOnLeave;

Solution

  • linkIdOn's scope is limited to cambioColorOnMouseover. But that is not your only problem. You need to move several things around.

    My suggestion:

    for(var linkId = 1; linkId < 5; linkId++) {
        document.getElementById('link'+linkId).onmouseover = function() {
            this.style.backgroundColor = "#eee";
            console.log(this.id);
        };
        document.getElementById('link'+linkId).onmouseout = function() {
            this.style.backgroundColor = "#ccc";
            console.log(this.id);
        };
    }
    

    For the benefit of others who don't know the CSS3 way to do this (which, though the OP wants to do this in JavaScript, is the preferred way):

    #link1, #link2, #link3, #link4, #link5 {
        background-color: #ccc;
    }
    
    #link1:hover, #link2:hover, #link3:hover, #link4:hover, #link5:hover {
        background-color: #eee;
    }
    

    Though if you did the CSS, you would likely have a link class instead of using ids.

    (I´ve changed two small typos that prevented the example to work (the system tells me that edits must be at least 6 characters) Thanks for your help! - Rosamunda)