Reputation: 299
I have a one page website where I need the active link in the menu to be a different colour. Is there a way in this code to have it so when a link is clicked on, the background colour doesn't show on all links as is scrolls through the pages.
This is for smooth scrolling and changing the background colour of the links:
$('a').click(function (e) {
e.preventDefault();
var href = $(this).attr('href');
$("html:not(:animated),body:not(:animated)").animate({
'scrollTop': $(href).offset().top
}, 700, 'swing');
});
$('#nav a').click(function () {
$('#nav a').css("background-color", "");
$(this).css("background-color", "#333333");
});
This is for when the user manually scrolls through the page and the background colour on the links change:
$(window).scroll(function () {
var href = $(this).scrollTop();
$('.link').each(function (event) {
if (href >= $($(this).attr('href')).offset().top - 1) {
$('.link').not(this).removeClass('active');
$(this).addClass('active');
}
});
});
Here's the fiddle http://jsfiddle.net/MCka4/
Upvotes: 0
Views: 3814
Reputation: 230
You could do this easily with CSS For example you could determine which elements of the navigation are selected with an .active CSS class:
#nav a {
background-color: transparent;
}
#nav a.active {
background-color: #333333;
}
And then you could change your code to use the new CSS class you just created:
$('#nav a').click(function () {
$('#nav a.active').removeClass('active');
$(this).addClass('active');
});
$(window).scroll(function () {
var href = $(this).scrollTop();
$('.link').each(function (event) {
if (href >= $($(this).attr('href')).offset().top - 1) {
$('#nav a.active').removeClass('active');
$(this).addClass('active');
}
});
});
Upvotes: 1