views:

43

answers:

3

Hi. 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');
});

});

A: 

You want to write something like this:

var otherExpanded = $('.content-block.wide');
if (otherExpanded.length)
    //Do things
SLaks
+3  A: 

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.

Nick Craver
@Nick thanks a lot for the help I appreciate it
mtwallet
+1  A: 

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()

Dominic Barnes
This would not have the same behavior, currently his code collapses the current `wide` div when clicked, this removes that ability.
Nick Craver
@Nick, I'm afraid I don't see what you are talking about. My code first finds the current `wide` div, removes the `wide` class from it. Then it adds the `wide` class to the now current `wide` div. Please let me know if I misunderstand.
Dominic Barnes
@Dominic - If you clicked the current div and it had `.wide`, `toggleClass()` removes it...since you remove it from all then add, you're making the parent `.wide` every time, no possibility of collapsing it. This isn't what the OP had, you're removing the collapse ability by taking this route.
Nick Craver