Reputation: 352
I want an open-close function. If the <div>
is open it should close when I click it, and when I click it again it should re-open. JSFiddle
HTML
<div class='answer'>answer</div>
<div style='display:none'>
<textarea name='talking'></textare>
<input type='submit'>
</div>
Jquery
$('.answer').click(function(){
if($(this).next().css('display','none')){
$(this).next().css('display','block');
}else if($(this).next().css('display','block')){
$(this).next().css('display','none');
}
})
In this example the "if" clause is working (it opens), but the "else if" does not work (it does not close again).
Upvotes: 2
Views: 44
Reputation: 240878
Within your conditional statements, you should be retrieving the element's display
property and comparing it with a string of the properties' value.
So that rather
if ( $(this).next().css('display', 'none') ) {
// ...
}
It should be:
if ( $(this).next().css('display') === 'none' ) {
// ...
}
$('.answer').click(function () {
if ($(this).next().css('display') === 'none') {
$(this).next().css('display', 'block');
} else if ($(this).next().css('display') === 'block') {
$(this).next().css('display', 'none');
}
});
Your code could be simplified to the following, though:
$('.answer').on('click', function () {
$(this).next().toggle();
});
The .toggle()
method handles all this logic.
Upvotes: 2