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');
});
});
You can do that like this, no need for an if in this case:
This toggles the wide class on the parent, then removes the class from all it’s siblings.