Javascript button listener fires once?

I am creating a slide show rotator for the website I am creating. The rotator itself works fine, but I'm trying to make the slide show slide forward / backward using the left / right keys on the keyboard. My code is:

$(document).keydown(function(e){ var currentPosition = 0; var slideWidth = 836; var slides = $('.slide'); var numberOfSlides = slides.length; var animLength = 600; if (e.keyCode == 37) { currentPosition = currentPosition-1; // Check to see if new position is unbounded, and wrap accordingly. checkForEnds(currentPosition); // Move slideInner using margin-left $('#slideInner').animate({ 'marginLeft' : slideWidth*(-currentPosition) }, animLength, 'easeOutExpo'); animLength=600; return false; } /*Same code for right button, removed to save space.*/ function checkForEnds(position){ // If left is clicked on first slide, wrap to end. if(position==-1){currentPosition = numberOfSlides-1, animLength=1000} // If right is clicked on last slide, wrap to beginning. if(position==numberOfSlides){currentPosition = 0, animLength=1000} } }); 

My code works fine, but only once. I can rotate the left one or once once, but after that I cannot reuse the same key until another one is pressed. I'm very new to Javascript input, is there a simple fix for this?

Here is a temporary site. This is a mess now, but I can take care of all the weird order of things and the layout of the problem is pretty good. http://technoheads.org/test/ice/

+6
source share
3 answers

Ok, I did it.

This has nothing to do with the fact that you are binding an event; the event fires correctly, but the equation you use to calculate the position is incorrect.

You define currentPosition var inside the block; therefore, it is determined every time the event is triggered; therefore, you will always get the same value after it starts.

What I did to solve this is move currentPosition to global space.

Take a look here: http://jsfiddle.net/kuroir/SSd3r/

Also note: it is important that you use the debugger when working with such problems, I highly recommend that you use Google Chrome for this.

+5
source

Each time the keydown event is fired, you override 'currentPosition' regardless of your current position in the slides. Although this is not the only problem with the code, it will cause most of the odd behavior. First fix this question and work from there. Sean is right, use a debugger and set breakpoints.

+1
source

Do you know how to use a debugger? In chrome, press ctrl + shift + j and select the scripts tab. Go to your code and set up a bunch of breakpoints. Refresh the page ... you can see what is happening in real time.

0
source

Source: https://habr.com/ru/post/887883/


All Articles