Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum amount of characters in a div/paragraph tag [closed]

I've created a 'New system' and I'd like the home page to show up to 300 characters per news article, and add an hyperlink "Read more" automatically at the end of the 300 characters (if needed). However, how would I do this?

I do not know what it is called and I couldn't find an answer on my question by just googling. I did find similair questions, like: Limiting the no of characters in a div has specific class But it doesn't completely fit my question.

Here is an example what it should look like:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cil**...Read more**

Thanks in advance!!

like image 698
Stefan R Avatar asked Oct 17 '13 11:10

Stefan R


1 Answers

jQuery way:

If you want to put only 300 characters, then you must use jQuery framework or pure Javascript.

Note: just change #your-div-id and put your div ID.

var myDiv = $('#your-div-id');
myDiv.text(myDiv.text().substring(0,300))

.

Pure JavaScript way:

Note: just change #your-div-id and put your div ID.

var i;
var divs = document.getElementById('#your-div-id');
for(i=0;i<divs.length;i++) {
  if(divs[i].className == 'myclass') {
    divs[i].innerHTML = divs[i].innerHTML.substring(0,300);
  }
}

Add Read More at the end:

if you want to add Read More at the end of each substringed paragraph, then you need to use pure Javascript or jQuery ways:

jQuery way:

var myDiv = $('#your-div-id');
myDiv.text(myDiv.text().substring(0,300) + '<a href="#">Read more</a>')

.

Pure JavaScript way:

var i;
var divs = document.getElementsById('#your-div-id');
for(i=0;i<divs.length;i++) {
  if(divs[i].className == 'myclass') {
    divs[i].innerHTML = divs[i].innerHTML.substring(0,300) + '<a href="#">Read more</a>';
  }
}

FYI

Also there is a pure CSS way to substring text in box, but it has no option to manually put character limit:

CSS way:

You can achieve this by pure CSS:

#your-div {
  text-overflow:ellipsis;
}

it will automatically cut text and put ... at the end of the box.

Please note, that it will not restrict browser to put only 300 characters. It will just fill the box.

like image 50
zur4ik Avatar answered Nov 05 '22 05:11

zur4ik