views:

18

answers:

2

Hi,

in my blog some articles are very long. So I want the long articles to be collapsed when the page is loaded. It works for me for just one article but if I have more articles something seems to be broken.

Here's how I do it:

$('div#ttoggle').hide();
$('#btoggle').click( function() {
    if($('div#btoggle p').text() == 'expand article'){
        $('div#btoggle p').text('collapse article');
    }else{
        $('div#btoggle p').text('expand article');              
    }   

    $('div#ttoggle').slideToggle("slow");           
});

Any ideas?

+1  A: 

You seem to be using an id selector for something which you state will appear multiple times on the page. id attributes must be unique, so this would be invalid HTML and could be causing this to fail.

The solution here would be to replace all ids with classes. You can use the .classname selector to select the appropriate elements

Yi Jiang
+1  A: 

You are using ids "#btoggle" where you probably want classes. You should only ever have a single element with a given id.

You are assigning a click handler to a number of elements, but then deciding what to do by examining all the element afresh. Instead use this inside your handler to only consider the clicked element:

$('div#ttoggle').hide();
$('#btoggle').click( function() {
    var tog = $(this);
    var togp = tog.find("p");    
    if (togp.text() == 'expand article') {
        togp.text('collapse article');
    }
    else {
        togp.text('expand article');              
    }   

    tog.siblings('div#ttoggle').slideToggle("slow");
});

(I don't know what your HTML actually looks like, I took a guess at the siblings.)

Ned Batchelder
thanks, but I have a "p" element inside the div#btoggle. so I need to set the text of the p element. how do I do that?
ArtWorkAD
sorry, fixed it.
Ned Batchelder