Skip to content Skip to sidebar Skip to footer

How To Achieve Active State In A Navigation For A One Page Website

I am working on a one page website. In this website, I would like to have the active section or 'page' to be underlined in the navigation bar. Currently I have the link to display

Solution 1:

you just forgot to add jquery and set the code to run on dom ready: http://jsfiddle.net/GdePr/8/

$(function(){
    $('#navbar a').click(function () {
        $('#navbar a').css('text-decoration', 'none');//don't forget to reset other inactive links
     $(this).css('text-decoration', 'underline');
     });
 });

But what i would suggest is to add the class active to the selected link and give it underline property in your CSS file so you can later in your script recognize current active link:http://jsfiddle.net/GdePr/14/

$(function(){
    $('#navbar a').click(function () {
        $('#navbar a').removeClass('active');
        $(this).addClass('active');
     });
 });

CSS:

a.active{
       text-decoration: underline !important; 
    }

Solution 2:

I disagree with MaveRicks answer slightly. You do need to wrap the code in a ready() function. However, to reset the other links, I would not jump into the DOM again. Make use of jQuery's siblings() function. It gets the elements on the same DOM level as the selected element, then does the specified function. By doing this, you are preventing the link you are clicking on to have two functions performed.

The selector would also take advantage of parent()

$(document).ready(function () {
    $('#navbar a').on("click", function () {
        $(this).parent().siblings().find("a").removeClass('active');
        $(this).addClass('active');
    });
});

This finds the parent of the a, which would be the li. Then, it gets all of the siblings of the li, so this doesn't include the li of the a that was clicked. Then it finds all of the as inside of those siblings. This will prove to be much more of a reusable function.

Fiddle

Also, don't use !important. It can cause many problems for you down the road

Solution 3:

Can you try defining an active state for your links

#navbara:active {text-decoration:underline;}

Post a Comment for "How To Achieve Active State In A Navigation For A One Page Website"