Reputation: 837
I have the following HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TestPost</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="more.js"></script>
</head>
<body>
<div class="post1">
This is post one
</div>
<div class="post1">
Another post number one
</div>
<div class="post2">
And this is post two
</div>
<div class="post3">
Last but not least, post three
</div>
</body>
</html>
What i'm looking for is the folowing: When the text in a div is longer that, lets say, 5 chars, it should cut it off and add ...read more(including a link to a page).
I tried some PHP and some JQuery, but to be honest, I'm not sure anymore what to use.
If I could get the answer, that would be fantastic, but a push in the right direction would be very appreciated as well :)
Edit: The second post1 was added for testing purposes for anyone who's wondering.
Upvotes: 0
Views: 2724
Reputation: 179
Use attribute class
instead of id
. replace id='post'
with class='post'
Use this code into your more.js
var mess_content = $('.post');
mess_content.each(function(){
if ($(this).text().length > 120) {
var obrtext = $(this).text().substr(0,120) ;
$(this).html(obrtext+"<a href='#'>read more</a>") ;
}
});
Upvotes: 2
Reputation: 696
To do this with PHP, when you ouput your text, run it through a shortening function like this:
function shorten($output, $limit = 5) {
$output = htmlspecialchars($output, ENT_QUOTES, 'UTF-8');
if (strlen($output) > $limit) {
$output = substr($output, 0, $limit) . ' <a href="#">... read more</a>';
}
echo $output;
}
You can use it then like this:
<div id="post1">
<?php shorten('This is post one'); ?>
</div>
Upvotes: 2