Q:

Show read more link if the text exceeds a certain length using jQuery

0

Show read more link if the text exceeds a certain length using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JavaScript substring() method

You can use the JavaScript substring() method in combination with the jQuery append() and html() methods to truncate the paragraphs of a text and add read more link at the end, if the number of characters inside a paragraph exceeds a certain length.

The jQuery code in following example will simply trim the paragraph and add read more link at the end. You can view the trimmed content by clicking the read more link.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Read More Link</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    var maxLength = 300;
    $(".show-read-more").each(function(){
        var myStr = $(this).text();
        if($.trim(myStr).length > maxLength){
            var newStr = myStr.substring(0, maxLength);
            var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
            $(this).empty().html(newStr);
            $(this).append(' <a href="javascript:void(0);" class="read-more">read more...</a>');
            $(this).append('<span class="more-text">' + removedStr + '</span>');
        }
    });
    $(".read-more").click(function(){
        $(this).siblings(".more-text").contents().unwrap();
        $(this).remove();
    });
});
</script>
<style>
    .show-read-more .more-text{
        display: none;
    }
</style>
</head>
<body>    
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <p class="show-read-more">This is a very long paragraph...</p>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get current image size (width & height) in ... >>
<< How to get substring from a string using jQuery...