0

Say I have written code as follows:

function over(i) {
    var num = -100 * i;
    var show = document.getElementById("ha");
    show.style.top = num.toString() + "px";
}

function leave() {
    var show = document.getElementById("ha");
    show.style.top = "0px";
}

function slideShow() {
    var refs = document.getElementsByTagName("a");
    var show = document.getElementById("ha");
    show.style.position = "absolute";
    show.style.left = "0px";
    show.style.top = "0px";
    // refs[0].onmouseover = function () {
    //     over(0);
    // };
    // refs[1].onmouseover = function () {
    //     over(1);
    // };
    // refs[2].onmouseover = function () {
    //     over(2);
    // };
    for (i = 0; i < refs.length; ++i) {
        refs[i].onmouseover = function () {
            over(i);
        };
        refs[i].onmouseleave = function () {
            leave();
        };
    }
}

addLoadEvent(slideShow);

I want to show a certain area of an image according to which <a> the mouse is over. However, it seems all i in the over(i) inside refs[i].onmouseover is set to 3, which is refs.length. Anyone could help me? I'm totally a rookie in script languages.

Einiemand
  • 302
  • 1
  • 8
  • 1
    Short answer: `for (i = 0` => `for (let i = 0`... – georg Oct 30 '18 at 17:40
  • 2
    The linked question's answers show you what to do. Side note: Your code is falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html). Declare your variables in the appropriate scope (in this case, as georg says, within the `for` using `let` (not `var`) in any modern environment (so, not any version of IE). Not declaring them, in loose mode, makes them globals. – T.J. Crowder Oct 30 '18 at 17:44

0 Answers0