0

I have this code and i don't understant why my var i is equal to linksLen when i try to use it, can you explain to me please why?:

var links = document.getElementsByTagName('a'), 
linksLen = links.length;

for (var i = 0 ; i < linksLen ; i++) {

    links[i].addEventListener('keydown',function(e){

         if(document.getElementById('overlay').style.display =='block'){
             if (e.keyCode === 39) {
            alert(i);
            }
        }   


    });
}

};

Max G
  • 135
  • 1
  • 1
  • 6
  • Maybe you mean `mousedown` instead of `keydown`, since `keydown` refers to the keyboard? See this fiddle for example: https://jsfiddle.net/5nkb4dqc/ – Emil S. Jørgensen Feb 16 '16 at 11:19
  • 1
    @EmilS.Jørgensen: Why do you think Max means `mousedown`? What would a keyCode of 39 mean in such an event? – Lightness Races in Orbit Feb 16 '16 at 11:21
  • It's just that you don't usually type in Anchor elements. The element is not designed to capture the cursor like a form element. If you want to listen for a keycode, listen on the window or on an input element like `textarea`. http://www.w3schools.com/html/html_links.asp http://www.w3schools.com/jsref/event_onkeydown.asp – Emil S. Jørgensen Feb 16 '16 at 11:30
  • Also, you would properly want to assign the listener in a closed scope (as i do in the fiddle), so that `i` doesn't get overridden on each loop and you end up only having a reference to `i` at its peak size. – Emil S. Jørgensen Feb 16 '16 at 11:32

0 Answers0