2

Well I have a menu and there I want to have an class called active, when its active, obviously.

To toggle this class I am using the jQuery toggle function, but it does just activate it in the js element. If I check the dom element, this class is never set. But I need this class, because of my CSS styles.

I know that there are already many topics about toggleClass jQuery, but they doesn't fit (at least I couldn't find anything suitable)

Here some code:

$('#menu').on('click', '.tab span', function (e) {
    e.stopPropagation();
    var $tab = $(this).parent('.tab');
    $tab.siblings('.tab.active').removeClass('active');
    $tab.toggleClass('active');
});

HTML markup

<div id="menu">
    <div class="tab">
        <span></span>
    </div>
</div>

Its working in all browsers, except IE8 Thanks in advance.

3
  • 2
    What doesn't work about it? how are you testing that the class isn't being applied?
    – Kevin B
    Commented May 21, 2013 at 14:01
  • Havn't tested this theory, but I seem to recall a similar issue and solving with something like having a "base" class to "alternate/toggle" with my "active" class. Try something like that, I "think" it might help. Been a long time since I've seen the issue, but I do recall it, and I swear I handled it with something like .toggleClass("base active") where base was dropped while active was added or vice versa.
    – SpYk3HH
    Commented May 21, 2013 at 14:02
  • 1
    Also, since you're using "removeClass" the way you are, you have no "real need" for toggleClass here. You would do just as well to replace that line with addClass. And the line $tab.siblings('.tab.active').removeClass('active'); is not going to remove active from itself ...
    – SpYk3HH
    Commented May 21, 2013 at 14:03

2 Answers 2

1

Try this instead:

$('#menu').on('click', '.tab span', function (e) {
    e.stopPropagation();
    var $tab = $(this).parent('.tab');
    $tab.addClass('active').siblings('.tab').removeClass('active');
});
0

Try this:

$('#menu').on('click', '.tab span', function (e) {
    e.stopPropagation();
    var $tab = $(this).parent('.tab');

    // remove active from all tabs
    $('#menu .tab').removeClass('active');

    // make current tab as active
    $tab.addClass('active');
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.