Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable keyCode for 1st and last element

I have made a onkeydown function which runs li elements blocks horizontally it runs perfectly but i need when the first and last li blocks in focus the left and right keys should get disable.

could anyone suggest a corrent way? 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;
            }

        });
  }

});

the working reference is jsfiddle

like image 621
matthewb Avatar asked Dec 04 '12 10:12

matthewb


1 Answers

I did it by using a counter the value of which is checked each time the user presses left or right. The counter is simply the number of li elements inside the ul tag.

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

Then only run the animation if we're within the values of the counter:

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 the jsFiddle too.

like image 86
Antti29 Avatar answered Nov 07 '22 13:11

Antti29