jquery - Active link on a one page website -
i have 1 page website need active link in menu different colour. there way in code have when link clicked on, background colour doesn't show on links scrolls through pages.
this smooth scrolling , changing background colour of 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 when user manually scrolls through page , background colour on 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 fiddle http://jsfiddle.net/mcka4/
you css example determine elements of navigation selected .active css class:
#nav { background-color: transparent; } #nav a.active { background-color: #333333; }
and change code use new css class 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'); } }); });
Comments
Post a Comment