Reputation: 425
I have the following code
<div class="side-box">
<h1>Main Title</h1>
<h2>Secondary Title</h2>
<p>
This is paragraph 1<br><br>
This is paragraph 1<br><br>
This is paragraph 3<br><br>
</div>
I'm trying to write a jQuery function that will display anything up to the first paragraph and then display the rest when a 'read more' link is clicked.
The content is generated by a WYSIWYG editor, otherwise i'm sure I would be able to create this function myself.
Upvotes: 3
Views: 4519
Reputation: 233
You can do this with CSS ( IE >= 9, because of the first-of-type ) - for reference check support here - Can I Use first-of-type
.side-box p:first-of-type ~ * {
display:none;
}
The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent. ( IE 7+ )
General sibling selectors documentation
Upvotes: 0
Reputation: 11044
Example working with your current HTML.
$('.side-box p').first().each(function(i,e){
htmlchunks = $(this).html().split('<br><br>');
first_part = htmlchunks.shift();
secondpart = $('<div class="hidden"/>').hide().html(htmlchunks.join('<br><br>'));
$(this).html(first_part + '<a class="readmore">read more</a>').append(secondpart);
});
$('.readmore').click(function(){
$(this).next('.hidden').show();
$(this).detach();
});
Yikes, though.
Upvotes: 0
Reputation: 13134
$('.side-box > p').not(':first-child').hide();
But you dont have more than 1 paragraph in your code, do you mean after first break(br)?
You can remove everything after first BR by using:
var str = $('.side-box p').html();
var substr = str.split('<br>');
$('.side-box p').html(substr[0]);
It searches the P, and splits it by the BR tags.
Then we take the first split and replace the p content with it :)
Upvotes: 4
Reputation: 66415
Add a "show link" for all paragraphs and hide the paragraph itself:
var paragraphs = $(".side-box > p");
paragraphs.before(function () {
return $("<a>Read more</a>").click(function () {
// hide the "Read more" link. Alternatively, use .remove() to remove the link
$(this).hide();
// this link was inserted before the paragraph, so displaying the next element
// (= paragraph)
$(this).next().show();
});
});
// hide the paragraphs which are now preceded by a "Read more" link
paragraphs.hide();
Upvotes: 0
Reputation: 45083
UPDATE:
I just noticed the paragraphs aren't actually paragraphs in the sense of p
tags (which define a paragraph in mark-up) - though what you ask for will still be possible, it might be a better consideration to fix the way content is being paragraphed in your editor.
The following ought to do the tick...
var paragraph = $("p:eq(0)").html();
Though you might want to play with html()
, text()
and val()
calls, I never get the correct one first time.
Upvotes: 1