Question

I want to know how to correctly write an if statement with jquery. I have a bunch of div's with an anchor in each that when clicked expands the the div's width using toggleClass. This works fine but I want to write an if statement that checks to see if the other div's have the same class applied, if so contract that div, then expand the next div (hope that makes sense), my code so far:

HTML:

<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>
<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>
<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>
<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>

JQUERY:

$(document).ready(function(){
$('a.expand').click(function(){
    $(this).parent('.content-block').toggleClass('wide');
});

});

Was it helpful?

Solution

You can do that like this, no need for an if in this case:

$(document).ready(function(){
  $('a.expand').click(function(){        
    $(this).parent('.content-block').toggleClass('wide')
           .siblings('.wide').removeClass('wide');
  });
});

This toggles the wide class on the parent, then removes the class from all it's siblings.

OTHER TIPS

No need for an if statement, just run removeClass() on anything that has the wide class applied to it:

$(document).ready(function(){
    $('a.expand').click(function(){
        $('.content-block.wide').removeClass('wide');
        $(this).parent('.content-block').addClass('wide');
    });
});

And for performance sake, just use addClass() and removeClass() instead of toggleClass()

You want to write something like this:

var otherExpanded = $('.content-block.wide');
if (otherExpanded.length)
    //Do things
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top