views:

48

answers:

3

Hi all,

Working with an API that spits out the contents in p tags ... but it gets too long. Thinking of hiding them upon reaching a limit of 400 characters, but that's not a good idea since there is a possibility of it cutting through a HTML tag.

So I'm trying to hide the rest of the content after 3 paragraphs instead and with a text "Read More" that will unhide the rest of the content. How would one accomplish this?

+2  A: 
<div><p></p><p></p><p></p><p></p><p></p>
    <a href="#readMore" class="readMore">Read More</a>
</div>

if you have this kind of structure, you can

$('div p:nth-child(3)').nextAll('p').hide();

and

$('a.readMore').click(function(){
    $(this).siblings('p').show();
    return false;
})

resources: - .nextAll()

Reigel
thanks, just what I needed
InYourDreamz
nice, this looks good!
Garis Suero
+3  A: 

You could use the :gt() selector and then .hide() or .remove() them:

var $content = $("#content");
$content.find("p:gt(2)").hide();

Or you could just hide all children elements beyond the third using .children() and .slice(3):

$content.children().slice(3).hide();

If you store the hidden elements you can even create your read more button very easily:

var $content = $("#content");
var $hiddenText = $content.children().slice(3).hide();
if ($hiddenText.length) {       
    var $button = $("<a href='#'>Read More...</a>").click(function() {
        $hiddenText.show();
        $button.remove();
        return false;
    }).appendTo($content);
}

View jsFiddle demo

gnarf
thanks, needed something simpler :)
InYourDreamz
A: 

This is slightly a backwards approach but do something like this.

<style>
#con p{
  display:none;
}
</style>

<div id='con'>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>

Then have jquery select the first three p tags and set the display to block.

Also, you could use

<style>
#con{
  overflow:auto;
  max-height:300px;
}
</style>

And you wouldn't have to worry about any of it.

qw3n
the problem with this is if javascript is disbled, you can't show what is hidden. So better hide things with jQuery then show it when needed.. ;)
Reigel
hmm good point. Didn't think about that.
qw3n