holyredbeard
holyredbeard

Reputation: 21208

Adding / removing class with slideToggle

When clicking on a heading a menu (ul/li) is slided down / up with slideToggle. As background of the heading I have an arrow pointing down if menu isn't visible, up otherwise (I have two classes, 'arrow-up' and 'arrow-down' for the background).

Below is what I've tried but it doesn't work. What would be a good solution?

$j('h3.sub-menu-dropdown-btn').click(function(){

    if ($j('ul').is(":visible")) {
        $j(this).removeClass('arrow-up');
        $j(this).addClass('arrow-down');
    } else {
        $j(this).removeClass('arrow-down');
        $j(this).addClass('arrow-up');
    }

    $j('.sub-menu-dropdown').slideToggle('fast');

});

Upvotes: 3

Views: 4257

Answers (3)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You need to use like this:

if($j("ul").is(":visible")==true){

Upvotes: 0

sfyn
sfyn

Reputation: 706

Try using hasClass(): https://api.jquery.com/hasClass/

$j('h3.sub-menu-dropdown-btn').click(function(){

    if ($j('ul').hasClass('arrow-up')) {
        $j(this).removeClass('arrow-up');
        $j(this).addClass('arrow-down');
    } else {
        $j(this).removeClass('arrow-down');
        $j(this).addClass('arrow-up');
    }

    $j('.sub-menu-dropdown').slideToggle('fast');

});

Also, and I cannot verify this without seeing the html markup, the selector $j('ul') may be too general.

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You could try that and see if it fits your needs:

$j('h3.sub-menu-dropdown-btn').click(function(){
    var $self = $j(this);
    $j('.sub-menu-dropdown').slideToggle('fast', function(){
        $self.toggleClass('arrow-up arrow-down');
    });
});

Upvotes: 4

Related Questions