How to unbind click event on the active element and bind again when another element is clicked?
I guess it's easier to explain using an example:
HTML:
<div class="boxset">
开发者_运维知识库 <div class="box_header">
h1
</div>
<div class="box">
This is some text for box 1.
</div>
</div>
<div class="boxset">
<div class="box_header">
h2
</div>
<div class="box">
This is some text for box 2.
</div>
</div>
<div class="boxset">
<div class="box_header">
h3
</div>
<div class="box">
This is some text for box 3.
</div>
</div>
JS:
$('.box_header').bind("click", function() {
$('.box').not($(this).next('.box')).animate({
'width': 'hide'
});
$(this).next().animate({
'width': 'show'
});
});
jsFiddle:
http://jsfiddle.net/rDHMF/
Here is a simple sideways accordion menu. Now when I click on a header (h1, h2, h3), its corresponding content will show and the previously opened one will close. However, I can click again on that same header I just clicked and it will contract and expand itself.
Is it possible to temporarily unbind the click event on the header I just clicked so that the 'active' header will just stay put when I click on it? Then bind again when I click on another header. If yes, how?
This should do:
$('.box_header').bind("click", function() {
$('.box').not($(this).next('.box')).animate({
'width': 'hide'
});
$(this).next().animate({
'width': 'show'
});
});
You don't need to un/rebind the events, just prevent the box from contracting when it's the same
I would do that in a different way. Whenever a user clicks on a header add an active
class to the header (and remove it from other headers). And do some other thing if this header already has an active
class (only remove a header from this header and animate). This way also allows us to customize styles on active headers.
精彩评论