sushil bharwani
sushil bharwani

Reputation: 30177

jQuery logic for unclicked paragraphs

i have following html structure.


<p class="expandableContent" ><span class="label">Computer and Laptop Repairs</span></p>
<div style="clear: both;"> </div>
<div class="services">content</div>

<p class="expandableContent" ><span class="label">Softrware and Hardware</span></p>
<div style="clear: both;"> </div>
<div class="services">content2</div>


So i have repetetion of content1 content2 content3 etc. I am writting a toggle function so that when i click on first paragraph first content div expands. When i click on second paragraph second expands but all other open content collapses.

Can somebody help.

Upvotes: 0

Views: 77

Answers (3)

Ender
Ender

Reputation: 15221

This should do the trick for you:

$(function() {
    $('.expandableContent').click(function() {
        $('.services').hide();
        $(this).nextAll('.services:first').show();
    });
});

First, you'll hide all .services divs, then select the next one after the paragraph that was clicked, and expand it.

Here's a demo of that in action: http://jsfiddle.net/Ender/5nYpT/

Upvotes: 1

James Kovacs
James Kovacs

Reputation: 11651

You can do it without modifying your HTML too.

$(document).ready(function() {
    $('.services').hide();
    $('.expandableContent').click(function() {
        $('.services:visible').toggle();
        $(this).nextAll('.services:first').toggle();
    });
});

The code should be mostly self-explanatory. By selecting only the visible .services, I can toggle them to hidden. I then used the nextAll() to find all following siblings with the class, .services, but only take the first. (I can't use next() as it only takes the immediately following sibling and then filters it by class. Not what we want.) I then toggle this between visible and hidden. You can find a working example at http://jsfiddle.net/Lv2mW/.

Upvotes: 1

shoebox639
shoebox639

Reputation: 2312

$('.expandableContent').click(function() {
    $('.services').hide();
    $('.services', this).show();
});

Also add these to your html:

<div class="expandableContent">
  <p>....</p>
  <div style="clear:both;"></div>
  <div class="services">content</div>
</div>

Upvotes: 1

Related Questions