saggiatore
saggiatore

Reputation: 31

Revealing content of a list of items with jquery

I am new to JQuery and would love some help on an issue. I have a div with some content that I want to expand and contract when you click a certain link. Its something like:

<div class="container">
<div class="cont-top">
<a class="morelink" href="#">More</a>
</div>
<div class="cont-btm">
<p>This is the content to be displayed</p>  
</div>
</div>

The issue is this container div is generated dynamically by a php loop. How do I write the jquery to open just a single instance of this div? Here is what I have, that works but obviously it is opening all the divs not just the one clicked.

$('.cont-btm').hide();
$('.morelink').click(function(e) {
e.preventDefault();
$('.cont-btm').toggle('fast');
});

I know this is a simple question but I am new to programming Thanks.

Upvotes: 2

Views: 61

Answers (4)

Jeff Fabiny
Jeff Fabiny

Reputation: 325

If you cannot add a class name (or id) to this div, can you find which number element it is in the page? That is, the first, second, third, etc. div? If so, you can use jQuery's pseudo selectors to get the div. For example :nth-child is a good one. If you cannot find the number, then since there is no unique identifyer you can't do this without going through a very round-a-bout way, such as comparing the html string in the divs content and then performing the eventhandler on a match. The key is making that element unique in some way.

Upvotes: -1

Siamak Motlagh
Siamak Motlagh

Reputation: 5136

Change the code like this:

    $('.cont-btm').hide();
    $('.morelink').click(function(e) 
    {
        e.preventDefault();
        $(this).parent().next().toggle('fast');
    });

Upvotes: 0

Vapire
Vapire

Reputation: 4578

You could use relative traversing for the div, like so:

$('.moreinfo').click(function(e) {
    e.preventDefault();
    $(this).parent().next('.cont-btm').toggle('fast');
});

Upvotes: 1

John Koerner
John Koerner

Reputation: 38087

You can use the next method:

$('.cont-btm').hide();
$('.morelink').click(function(e) {
    e.preventDefault();
    // get the parent of the link and then get the next .cont-btm after the parent.
    $(this).parent().next('.cont-btm').toggle('fast');
});​

Sample fiddle: http://jsfiddle.net/johnkoer/EGzCE/6/

Upvotes: 1

Related Questions