Reputation: 63
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
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
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
Reputation: 89
You can do it with addClass an removeClass functions of jquery.
$('selector').addClass('className');
$('selector').removeClass('className');
Upvotes: 0