March 17, 2012

Jquery last selector solution

Question by Dejo Dekic

I have created this Fiddle with this code:

This is my problem I want to make same behavior by selecting last li (fifth) tag but not the fourth like in this example ,but I don’t know how to accomplish that:(

I hope that someone can help me with this…THX!!

$(document).ready(function() {

 $("button").click(function() {
    $('.active').removeClass('active').next('li').addClass('active')
      if ($('ul li:last').hasClass('active')) {
          $('ul li:last').removeClass('active')
          $('ul li:first').addClass('active')
      }

  });


});

Answer by Rob W

You should put part in an else block. Otherwise, both methods will run twice for the last list item, causing the last element to be “skipped”.

A better solution (demo: http://jsfiddle.net/9dF22/5/ ):

$(document).ready(function() {
    $("button").click(function() {
        var $li = $('ul li'),
            $active = $li.filter('.active:first'),
            $next = $active.next();
        $active.removeClass('active');
        if ($next.length) {               // length === 0 if there is no next one
            $next.addClass('active');
        } else {
            $li.first().addClass('active');
        }
    });
});

Demo: http://jsfiddle.net/9dF22/3/

$(document).ready(function() {
    $("button").click(function() {
        if ($('ul li:last').hasClass('active')) {
            $('ul li:last').removeClass('active')
            $('ul li:first').addClass('active')
        } else {
            $('.active').removeClass('active').next('li').addClass('active')
        }
    });
});

Answer by Starx

I got much better way to do this

$("button").click(function() {
    if($('.active').next('li').length != 0) {
        $('.active').removeClass('active').next('li').addClass('active')
    } else {
        $('.active').removeClass('active');   
        $("ul li").first().addClass('active');
    }      
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!