ACarter
ACarter

Reputation: 5697

jQuery basic toggling only working one way

I've created some quick jQuery toggle code:

$("#expander.closed").click(function(){
    console.log("opening");
    $("#expander").removeClass();
    $("#expander").addClass("open");
});
$("#expander.open").click(function(){
    console.log("closing");
    $("#expander").removeClass();
    $("#expander").addClass("closed");
});

The idea is that everytime you click #expander the class toggles between open and closed.

However, for some reason, it only works once, changing from closed to open, and then goes no further.

I have no clue why. Here's a jsFiddle.

Upvotes: 1

Views: 600

Answers (3)

Salman
Salman

Reputation: 9447

I think in the beginning, when you bind the events, .closed class does not exists, so the event does not get bound

May be you should bind the event to some other criteria, or use live. which is deprecated though

Better way would be like this

$("#expander_parent").on('click', '#expander.closed', function(){
    // Do your stuff
})

Upvotes: 2

Tuan
Tuan

Reputation: 514

You can do this and add your other related operations within the if/else conditions

HTML:

<div id="expander" class="closed">Click Me</div>

CSS:

.closed {
    background-color: red;
}

.open {
    background-color: blue;
}

Javascript:

$("#expander.closed").click(function (){
    if ($('#expander').attr('class') === 'closed') {
          $('#expander').attr('class', 'open');

          // Add other related functions here
    } else {
        $('#expander').attr('class', 'closed');

        // Add other related functions here
    }    
});

http://jsfiddle.net/mCDwy/1/

Upvotes: 1

wirey00
wirey00

Reputation: 33661

Just bind it using the id and toggle the classes using .toggleClass

$("#expander").click(function(){
    $(this).toggleClass('open closed');
});

FIDDLE

if you need to do other functions depending on which class it has you can check like this

$("#expander").click(function(){
    var $this = $(this);
    $this.toggleClass('open closed');
    if($this.hasClass('open')){
       // do your open code
    }else{
       // do your close code
    }   
});

FIDDLE

Upvotes: 2

Related Questions