简体   繁体   中英

adding specific class to element on click jquery

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.

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:

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');
    });
});

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');
         }
     });
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM