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:
- get all outer containers of the elements that you want to shrink
- convert each element content to string
- store the original content in an array
- eliminate the html tags of each content
- shorten the string of each content
- add the „… read more“ text to the string
- store the shortend text in an array
- add an event listener „on click“:
- close all open containers with the click-> fill all containers with the short version
- get the full long content from the array and fill the clicked container
- done
First click opens the first container, second click on another container opens the clicked one and closes all others.
JavaScript/jQuery:
// 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() {
textTags.each(
function(j) {
$(this).html(treatedTxt[j]);
}
);
}
textTags.each(
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
shortVersion();
//this extend
$(this).html(fullTxt[i]);
});
}
);
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;
else
//shorten
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() {
$(this).html(inhaltText);
});
Author: Thomas Hezel, zazu.berlin 2021