Zum Inhalt springen

Add with jQuery a „… read more“ button to a sequence of shortend html elements

From many news plugins we know the „read more“ button in previews of articles. Sometimes in web development you want to have a good overview over the content but on the same time plenty of information. To make it just a headline and then, the rest follows on a click, is often not enough.

Here is a jQuery solution with a variable that defines the length of the teaser text.

The principle is as follows:

  1. get all outer containers of the elements that you want to shrink
  2. convert each element content to string
  3. store the original content in an array
  4. eliminate the html tags of each content
  5. shorten the string of each content
  6. add the „… read more“ text to the string
  7. store the shortend text in an array
  8. add an event listener „on click“:
    1. close all open containers with the click-> fill all containers with the short version
    2. get the full long content from the array and fill the clicked container
  9. done

First click opens the first container, second click on another container opens the clicked one and closes all others.


// read more, Mehr erfahren

var lengthTxt = 200;
var mehr = ' … <span class="blue mehrlink">read more</span>';
var fullTxt = [];
var treatedTxt = [];

//shorten Text and remove html-tags

//get the elements and shorten the text
var textTags = $('.shortenText');

//when you extend a tag the others should shrink back
function shortVersion() {
        function(j) {

    function(i) {
        var txtOut = $(this).html().toString();
        //store original content in array
        fullTxt[i] = txtOut;
        //remove html tags
        txtOut = txtOut.replace( /(<([^>]+)>)/ig, '');
        //shorten and add read more text
        txtOut = txtOut.substring(0, lengthTxt).concat(mehr);
        //store the shortend text
        treatedTxt[i] = txtOut;
        //add the click event to this tag
        $(this).html(txtOut).click(function() {
            // all shortend
            //this extend

In case you only need it for one container on a page you can make it more simple

var lengthText = 200;
var mehr = ' … <span class="blue mehrlink">read more</span>';

//shorten text and remove html-tags
function cutText (txt, lengTxt) {
    txtOut = txt.toString();
    if ((txtOut===null) || (txtOut===''))
      return false;
      txtOut = txtOut.substring(0, lengTxt);
      //remove html tags
      txtOut = txtOut.replace( /(<([^>]+)>)/ig, '');
      return txtOut.concat(mehr);

//get the elements and shorten the text
var textTag = $('.shortenText');

var inhaltText = textTag.html();
// output result
textTag.html(cutText(inhaltText, lengthText));

textTag.click(function() {

Author: Thomas Hezel, zazu.berlin 2021

    Schreibe einen Kommentar

    Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert