Question

Considering the following javascript:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function runMe(){
 for(var x=0; x<5; x++){
  var d=document.createElement("DIV");
  d.innerHTML="test " + x;
  d.tabIndex=x;

  d.onfocus=function(y){
   return function(){
    alert("focus: " + y);
   }
  }(x);

  d.onblur=function(y){
   return function(){
    alert("blur: " + y);
   }
  }(x);

  document.body.appendChild(d);

 }
}
</script>
</head>
<body onload="runMe()">
</body>
</html>

When run, the onblur event fires and alerts the index of the newly-focused div, rather than alerting the index of the previously-focused div.

Strangely enough, when I remark out the onfocus event, the onblur works as expected, alerting the previously-focused div.

I cannot seem to find out why the onblur event fires the same index as the onfocus event.

I believe my closures to be correct, but I'm not 100% on that.

Has anybody got some insight as to my error?

Was it helpful?

Solution

DEMO: http://jsfiddle.net/abc123/nCwDz/1/

Your code appears to be working to me...changed alert to console.log please use Firefox or Chrome and then go to the console to see it working.

To prove your closures are right I have changed your code to be indented appropriately.

CODE:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function runMe(){
                for(var x=0; x<5; x++){
                    var d=document.createElement("DIV");
                    d.innerHTML="test " + x;
                    d.tabIndex=x;

                    d.onfocus=function(y){
                        return function(){
                            console.log("focus: " + y);
                        }
                    }(x);

                    d.onblur=function(y){
                        return function(){
                            console.log("blur: " + y);
                        }
                    }(x);

                    document.body.appendChild(d);
                }
            }
        </script>
    </head>
    <body onload="runMe()">
    </body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top