1

My code would pretty much speak for itself about what I'm about to achieve but just to clarify...

I want to return an the input value after long press (mousedown for 200ms).

It's working perfectly outside the for loop but inside the the loop it seems like not.

For this.value it returned undefined and for gangina[i].value it returned nothing.

Here is the jsFiddle:

http://jsfiddle.net/hezi_gangina/nxao19oc/

Here is my code :

<input type=button value=1>
<input type=button value=2>

<script>

var hezi;
var gangina=document.getElementsByTagName("input");

alert(gangina[1].value); //THIS IS OK! :)

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

    gangina[i].onmousedown=function()
    {
        hezi=setTimeout
        (
            function()
            {
                alert('this = '+this.value); // = undefined
                alert('gangina['+i+'] = '+gangina[i].value); // = nothing
            },200
        );
    }

}

</script>

Small tweak needed here...

Hezi-Gangina
  • 637
  • 6
  • 20

1 Answers1

1

DEMO

You may need to wrap the function inside IIFE which will bind the i value.

Since the inner mousedown event handler will execute at some point, it will remember only the last value of i. Also note here that you've forgot to mention var infront of i as well.

If you want to assign the correct value of i, better wrap the inner function inside a IIFE function, now that event handler will refer to the locally scoped i at that moment. So it will always remember the correct value of i.

for(var i=0;i<gangina.length;i++)
{
   (function(i) {
    gangina[i].onmousedown=function()
    {
        var that = this;
        hezi=setTimeout
        (
            function()
            {
                alert('this = '+that.value); // = undefined
                alert('gangina['+i+'] = '+gangina[i].value); // = nothing
            },200
        );
    }
  })(i);

}

Also inside the setTimeout, this will refer to Window object not the DOM element.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47