javascript - Arrow key press statement not functioning correctly -


i'm trying create simple gallery web page consists of user pressing left , right arrow keys taking them previous/next image. far have code shown below. doesn't seem respond key presses though. i've checked console , there no errors, leaving me stuck issue is.

the .image div html not change on key press - ideas?

$(document).ready(function() {     var current = 1;     $("body").keydown(function(e) {     if(e.keycode == 37) {         if (current == 1) {             var current = 1;         } else {             var current = current - 1;         }         $('.image').html('<img src="images/' + current + '.jpg"/>');     }     else if(e.keycode == 39) {         var current = current + 1;         $('.image').html('<img src="images/' + current + '.jpg"/>');     }     }); }); 

html

<body>     <div class="image">         <img src="images/1.jpg"/>     </div> </body> 

i've tweaked it, current variable resetting on keydown. op has been edited - leaves me problem of current variable lisitng nan.jpg file names?

your problem current being undefined result of redefining current in various scopes of code. tricky programming bug called variable shadowing http://en.wikipedia.org/wiki/variable_shadowing

you should define variable current in 1 scope, reference in lower scope so:

$(document).ready(function() {     var current = 1;     $("body").keydown(function(e) {         alert(current);      if(e.keycode == 37) {         if (current == 1) {             current = 1;         } else {             current = current - 1;         }         $('.image').html('<img src="images/' + current + '.jpg"/>');     }     else if(e.keycode == 39) {         current = current + 1;         $('.image').html('<img src="images/' + current + '.jpg"/>');     }     }); }); 

see working fiddle http://jsfiddle.net/rtwm6/


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -