texi rv texi rv - 2 months ago 22
CSS Question

when it reached fourth tab it should not go to first


  • i am new to js

  • when i click the left and right arrows the tabs circle back

  • but the circle should stop. when it reached fourth tab it should not go to first.

  • similarly it should happen for left arow too.

  • providing my code below.



https://codepen.io/chandrashekhar/pen/mMGRbq

function move(to) {
var current = $('li.current').index();
var total = $('.tabs .tab-link').length;
var add;
switch (to) {
case 'left':
add = -1;
break;
case 'right':
add = 1;
break;
}
$('.tabs li.tab-link').eq((current+add)%total).click();
}

Answer Source

Here you go:

function move(to) {
  var current = $('li.current').index();
  var total = $('.tabs .tab-link').length;

  var add;
  switch (to) {
    case 'left':
      current > 0 ? add = -1 : add = 0;   // don't decrement if we're already at the leftmost tab
      break;
    case 'right':
      add = 1;
      break;
  }
  $('.tabs li.tab-link').eq((current+add)).click();   // removed modulus operator to prevent wrapping back to 0
}
  • I've added a condition to case 'left': to check if we're currently at the leftmost tab (index 0), and if so don't decrement any further.
  • I've removed the modulus (%) operator from $('.tabs li.tab-link').eq((current+add)).click(); to prevent the index from wrapping back to 0 when we click the right arrow with the rightmost tab activated.