Disable keyCode for the first and last elements

I made the onkeydown function, which runs blocks of li elements horizontally, it works fine, but I need it when the first and last li blocks in focus with the left and right keys should be disabled.

Can anyone suggest a root path? Thanx in advance !!!

$(document).ready(function() { var winht = $(window).height(); var contUl = $('.content ul').children('li').size(); var widLi = $('.content ul li').width(); var contUlAndLI = contUl * widLi; var leftIndex = $('.content ul').css('left','0'); $('.content ul').width(contUlAndLI); $('#frame').height(winht); $("body").keydown(function(e) { if(e.keyCode == 37) { // left $(".content ul").animate({ left: "-=980" }); } else if(e.keyCode == 39) { // right $(".content ul").animate({ left: "+=980" }); } }); if( leftIndex == 0){ $("body").keydown(function(e) { if(e.keyCode == 39){ // right //event.preventDefault(); return false; } }); } }); 

jsfiddle working link

+8
jquery jquery-plugins jquery-selectors
source share
1 answer

I did this using a counter, the value of which is checked every time the user clicks left or right. A counter is simply the number of li elements inside an ul tag.

 var ulCount = $('.content li').length - 1; var i = 0; 

Then start the animation only if we are within the counter values:

 if(e.keyCode == 37) { // left if (i < ulCount) { i++; $(".content ul").animate({ left: "-=980" }); } } else if(e.keyCode == 39) { // right if (i > 0) { i--; $(".content ul").animate({ left: "+=980" }); } } 

I updated jsFiddle .

+1
source share

All Articles