Egidi
Egidi

Reputation: 1776

javascript jquery accessing the element being clicked

I've got the following list of semibuttons loaded using javascript:

        var html ='<ul class="nav well-tabs well-tabs-inverse mb10" id="users">';

        html +='<li class="active"><a id="'+this.my.user+'" data-toggle="tab_'+self.my.id+'" class="pestaña">'+this.my.user+'</a></li>';
        var users = this.my.community_users;
        for (i=0;i<users.length;i++) {
            if (users[i].user != this.my.user)
            html +='<li><a id="'+users[i].user+'" data-toggle="tab_'+self.my.id+'" class="pestana">'+users[i].user+'</a></li>';
        };
        html +='</ul>';
        $(html).appendTo("#Dashboard");

Note, that the first item in the list is active. I am getting something like this:

image

Ok, now i code he onclick event to do something when a button is clicked:

$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function(e){
      // whatever here
});

What I need now is to set active the tab being clicked and set inactive the tab that was active. How can I access both elements to addclass and removeclass active?

Upvotes: 2

Views: 75

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

You could use following logic:

$(document).on('click', '#users li:not(.active)', function () {
    $('#users').find('li.active').add(this).toggleClass('active');
});

Upvotes: 3

arb
arb

Reputation: 7863

I would remove the 'active' class from all the list items first, then add it back to just the only that was clicked.

$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function (e) {
    $('#users .active').removeClass('active');
    $(this).addClass('active');
});

Upvotes: 0

kavun
kavun

Reputation: 3381

Something like this might work. Basically remove the .active class from everything but the element you clicked on. The add the .active class to the element clicked on.

$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function (e) {
    $('a[data-toggle=tab_'+self.my.id+']').not(this).removeClass('active');
    $(this).addClass('active');
});

Upvotes: 0

Related Questions