javascript - jquery prev and next adjacent sibling -


i create pagination add class next , previous element. generated code doesn't work well. think common situation, maybe using wrong code. how can improve code?

this fiddle http://jsfiddle.net/hhebhm66/

  var $curr = $( "div.active" );    $( ".prev" ).click(function() {      if ($($curr).is(':first-child')){       $('.prev').hide();     }else{       $('.next').show();       $curr = $curr.prev();       $( "div" ).removeclass('active');       $curr.addclass('active');      }   });     $( ".next" ).click(function() {      if ($($curr).is(':last-child')){       $('.next').hide();     }else{       $('.prev').show();       $curr = $curr.next();       $( "div" ).removeclass('active');       $curr.addclass('active');      }   }); 

your logic can improved using prev() or next() , checking element retrieved. if wasn't, first() or last() singling div in set. try this:

$(".prev").click(function () {     var $active = $('.active').removeclass('active');     var $prev = $active.prev('div');     if ($prev.length == 0)            $prev = $active.siblings('div').last();     $prev.addclass('active'); });   $(".next").click(function () {     var $active = $('.active').removeclass('active');     var $next = $active.next('div');     if ($next.length == 0)            $next = $active.siblings('div').first();     $next.addclass('active'); }); 

example fiddle


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -