Tarek Mostafa Tarek Mostafa - 7 months ago 13
Javascript Question

Using $(this) inside an if statement

I'm trying to make an accordion with 3 panels, so when I click on a panel its content should appear and when I click it again its content should disappear

Here is the jquery code

jQuery(".item").click(function() {

if ( jQuery(".content").css("display") == "block" )
{
jQuery(this).css("display", "none");
}

else if ( jQuery(".content").css("display") == "none" )
{
jQuery(this).css("display", "block");
}
}


But the problem here is that jQuery(this) here refers to the class ".item" of course, and the whole panel disappears when clicked.

So I want to refer to ".content" so that only the content of the panel that is being clicked should be displayed or not.

This is the HTML Code:

<div class="container">
<div calss="row">
<div class="accordion">

<div class="item">
<div class="content"></div>
</div>

<div class="item">
<div class="content"></div>
</div>

<div class="item">
<div class="content"></div>
</div>

</div>
</div>
</div>


I tried this

jQuery(".item").click(function() {

if ( jQuery(".content").css("display") == "block" )
{
jQuery(".content").css("display", "none");
}

else if ( jQuery(".content").css("display") == "none" )
{
jQuery(".content").css("display", "block");
}
}


but then when clicked, the contents of all the 3 panels appear/disapear. Any suggestions would be appreciated

Answer

If you pass this in the second argument of jQuery, it will find .content within this. Like so:

jQuery(".item").click(function() {

    if ( jQuery(".content", this).css("display") == "block" )
    {
        jQuery(".content", this).css("display", "none");
    }

    else if ( jQuery(".content", this).css("display") == "none" )
    {
        jQuery(".content", this).css("display", "block");
    }
})

Your click handler is finding ALL of the elements with the selector, so passing this will limit the scope to find the element to hide/show.

To optimize this code, try storing into variables because calling jQuery/$() can be expensive, especially if you need to access the element several times inside the handler. You can use the toggle function to toggle its state from visible to hidden and vice versa.

jQuery(".item").click(function() {

    jQuery(".content", this).toggle();
});
Comments