0

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.

HTML:

<div id="mainNav">
    <ul id="nav">
        <a id="mainLogo" href="/"><li></li></a>
        <a id="aboutLink" class="aLink" href="/"><li></li></a>
        <a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
        <a id="external" href="/"><li></li></a>
    </ul>
</div><!--/#mainNav-->

I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.

jQuery:

$(function () {
    $(".aLink").click(function () {
        if ($(this) == $("#aboutLink")
            $(this).addClass('activeLink');
         else $(this).addClass('active2Link');
         });
     });

Thanks for any input or direction.

3
  • 1
    if ($(this).is('#aboutLink')){...} Commented Jul 23, 2013 at 22:37
  • 1
    Add class(es) to which element(s)? Oh, and your HTML is horribly invalid: the only element that can be a valid child-element of either a ul or ol is an li. Put the a element inside the li elements. Commented Jul 23, 2013 at 22:38
  • add .linkActive to #aboutPage or add .link2Active to #sasPage Commented Jul 23, 2013 at 22:39

3 Answers 3

4
var idToClass = {
    'aboutLink' : 'linkActive',
    'sasLink' : 'link2Active'
}

$('#nav a').click(function(){
    e.preventDefault();
    $(this).addClass(idToClass[this.id]);
});

JS Fiddle demo.

You could, instead, use toggleClass() to allow for those classes to be removed by a second click:

var idToClass = {
    'aboutLink' : 'linkActive',
    'sasLink' : 'link2Active'
}

$('#nav a').click(function(e){
    e.preventDefault();
    $(this).toggleClass(idToClass[this.id]);
});

JS Fiddle demo.

Edited in response to question, from the OP, in comments, below:

How would I remove the class so that both links don't appear to be active at the same time?

There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:

$('#nav a').click(function(e){
    e.preventDefault();
    var self = $(this);
    self.closest('ul').find('a[class]').attr('class', '');
    self.toggleClass(idToClass[this.id]);
});

JS Fiddle demo.

The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:

$('#nav a').click(function(e){
    e.preventDefault();
    for (var id in idToClass) {
        if (idToClass.hasOwnProperty(id)){
            $('#' + id).removeClass(idToClass[id]);
        }
    }
    $(this).addClass(idToClass[this.id]);
});

JS Fiddle demo.

If, of course, you use a common class-name then it all becomes much easier:

$('#nav a').click(function (e) {
    e.preventDefault();
    var self = $(this);
    self.closest('ul')
        .find('.commonActiveClassName')
        .removeClass('commonActiveClassName');
    self.addClass('commonActiveClassName');
});

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the kind words! =)
How would I remove the class so that both links don't appear to be active at the same time?
1

Since you already have ID tags to easily reference... I think you want something more like this?

$(function () {
    $("#aboutLink").click(function () {
            $(this).addClass('activeLink');
    });
    $("#sasLink").click(function () {
            $(this).addClass('active2Link');
    });
});

Comments

0

Try using this instead:

$(function () {
    $(".aLink").click(function () {
        var currentId = this.id;
        if ( currentId == "aboutLink"){
            $(this).addClass('activeLink');
         else if( currentId == "sasLink") {
             $(this).addClass('active2Link');
         }
     });
 });

1 Comment

Please don't ever use $(this).attr('id') in real code; just use this.id. It's supported everywhere and it's cheaper to use. And far more concise to type (jQuery, after all, promotes the 'write less, do more' methodology, so why waste keystrokes, or CPU time?).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.