Reputation: 5697
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
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
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
}
});
Upvotes: 1
Reputation: 33661
Just bind it using the id and toggle the classes using .toggleClass
$("#expander").click(function(){
$(this).toggleClass('open closed');
});
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
}
});
Upvotes: 2