0

I'm having trouble getting the value of i to be passed on to the scMotion function

for ( i = 0; i < tmp.length; i++ ) {
document.getElementById("sc"+i).onmousedown=function() { return scMotion(i,'up') };
}

To clarify the question, this for loop is doing other stuff, adding elements to the dom.

For some reason even if i is at number 39 the value of i being passed in the function I ma attaching is the final value of i i.e 80.

Guesser
  • 1,769
  • 3
  • 25
  • 52

2 Answers2

6

That works as you typed it because there should be a closure between i and the function:

var i="4";
document.getElementById("sc"+i).onmousedown=function() {
    return scMotion(i,'up'); // <-- due to the created closure, the i here
                             //     refers to the i above.
};

However, remember that it's a closure. So perhaps the following scenario is what's tripping you up:

var i="4";
document.getElementById("sc"+i).onmousedown=function() {
    return scMotion(i,'up'); // <-- due to the created closure, the i here
                             //     refers to the i above.
                             //     However, when the event happens in the
                             //     future the value of i in here will
                             //     be "5" due to the code below:
};
i = "5";

This is a classic closure in a loop problem. See this to understand what's happening: Please explain the use of JavaScript closures in loops

Community
  • 1
  • 1
slebetman
  • 109,858
  • 19
  • 140
  • 171
0

Try instead to use addEventListener. You can use the id to pass the number to your function.

for ( i = 0; i < tmp.length; i++ ) {

    var el = document.getElementById( "sc" + i );

    if ( el.addEventListener ) {

        el.addEventListener( 'mousedown', handleMouseDown ); 

    } else if ( el.attachEvent )  { // for IE8 and previous versions

        el.attachEvent( 'mousedown', handleMouseDown );

    }
}

function handleMouseDown( event ) {

    var num = event.target.id.replace( "sc", "" );
    scMotion( num, 'up' );
}
Bruno
  • 5,772
  • 1
  • 26
  • 43