Shubham Jha
Shubham Jha

Reputation: 63

Add or Remove class using jQuery for scrolling navigation

This code helps me to scroll to a particular section when I click on my navigation tabs. In brief, it helps me to make a one page website. How can I add and remove active class to the navigation <li> tags in this code?

jQuery

$(document).ready(function() {
  $('ul').find('a').click(function(){
    var $href = $(this).attr('href');
    var $anchor = $($href).offset();
    $('body,html').animate({ scrollTop: $anchor.top }, 1000);
    return false;
  });
});

Upvotes: 0

Views: 297

Answers (3)

Renan Ara&#250;jo
Renan Ara&#250;jo

Reputation: 3631

You can delete all the .active from the li, then get the closest li and set the active class to it.

   $(document).ready(function() {
      $('ul').find('a').click(function(){
        var $href = $(this).attr('href');
        var $anchor = $($href).offset();
        $('body,html').animate({ scrollTop: $anchor.top }, 1000);
        // remove all .ative from lis
        $("ul li").removeClass('active');
        // set active class to the parent li
        $(this).closest('li').addClass('active');
        return false;
      });
    });

Upvotes: 1

PriyankJ
PriyankJ

Reputation: 117

You can use .parent('li') to get to parent of a and add active class to it. And then get all sibling of <li> using .siblings() and remove active class from them.

$(document).ready(function() {
  $('ul').find('a').click(function(){
    var $href = $(this).attr('href');
    var $anchor = $($href).offset();
    var $li = $(this).parent('li');
    $li.addClass('active');
    $li.siblings().removeClass('active');
    $('body,html').animate({ scrollTop: $anchor.top }, 1000);
    return false;
  });
});

Upvotes: 1

julian zapata
julian zapata

Reputation: 89

You can do it with addClass an removeClass functions of jquery.

$('selector').addClass('className');
$('selector').removeClass('className');

Upvotes: 0

Related Questions