Checking the position during each click and adding a class

I want the .disabled class to be added to the left and / or right controls (.tab-left, .tab-right) if the first or last tab is displayed, so that the user can see that they have reached the end and cannot click further.

Right now I have something like this to keep the user from going past the end.

if (tabs are at the end) {
   return;
 }

      

This works for users who can't get past the end, but if I add the class before returning, the problem is that the .disabled class is not added until the tabs reach the end and the user clicks again.

if (tabs are at the end) {
   $('.tab-right').addClass('disabled');
   return;
 }

      

I need the disabled class to be added when the last tab is displayed, not when the user tries to click on the nib.

Here's a link to the js fiddle: http://jsfiddle.net/uue6pgcx/

+3


source to share


1 answer


One option you can try is to enable / disable the right and left buttons after the animation ends.

$ul.filter(':not(:animated)').animate({
    "left": dir + liWidth
  }, {
    complete: function () {
    // Calculate the number of items in the container (without left and right navigation buttons).
    var lisContainer = Math.round(($container.width() - $left.outerWidth() - $right.outerWidth()) / liWidth);
    // Disable right button when list is moved to the left a number of items
    // such as the remaining number of them is less or equal than the number
    // of items that fit in the container.
    $right.toggleClass('disabled', $li.length + $ul.position().left / liWidth <= lisContainer);
    // Disable left button when list is in the origin. 
    $left.toggleClass('disabled', $ul.position().left === 0);
  }
});

      



Disclaimer : As per jQuery externalWidth additional notes , the number returned by the dimension related APIs, including .outerWidth (), may in some cases be fractional. The code should not assume that it is an integer. So let's hope that Math.round

will be enough to get the correct number. Perhaps there is a better way to calculate whether to disable / enable the right button instead of relying on the number of items that fit into the container.

Here is your code with the above modification: http://jsfiddle.net/0Lsepxeu/

+3


source







All Articles