user3301042
user3301042

Reputation: 352

else if clause is not working as expected

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

Answers (1)

Josh Crozier
Josh Crozier

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' ) {
    // ...
}

Updated Example

$('.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:

Example Here

$('.answer').on('click', function () {
    $(this).next().toggle();
});

The .toggle() method handles all this logic.

Upvotes: 2

Related Questions