Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
Advanced Search
  • 0

Adding a Read More/Read Less link to any text using HTML and Jquery


coverkitchen

Question

Site URL: https://coverkitchen.com/

Hi, Everyone

I have managed to add a Read More link to a text using a combination of HTML in a code block as text and adding a Jquery code to the page. The problem is that the Jquery ignores line breaks and styles applied  in the HTML code. So  the <br> and <i> will not work after the Jquery script loads. 
Is there any way to fix this adding a code line to the Jquery? If this is fixed, I am sure many users will find this code to be very useful. See my current Jquery for the Read More link is below:

Many thanks in advance!

 

<script>
    function AddReadMore() {
        //This limit you can set after how much characters you want to show Read More.
        var carLmt = 250;
        // Text to show when text is collapsed
        var readMoreTxt = " ... Read More";
        // Text to show when text is expanded
        var readLessTxt = " Read Less";
      
        //Traverse all selectors with this class and manupulate HTML part to show Read More
        $(".addReadMore").each(function() {
            if ($(this).find(".firstSec").length)
                return;

            var allstr = $(this).text();
            if (allstr.length > carLmt) {
                var firstSet = allstr.substring(0, carLmt);
                var secdHalf = allstr.substring(carLmt, allstr.length);
                var strtoadd = firstSet + "<span class='SecSec'>" + secdHalf + "</span><span class='readMore'  title='Click to Show More'>" + readMoreTxt + "</span><span class='readLess' title='Click to Show Less'>" + readLessTxt + "</span>";
                $(this).html(strtoadd);
            }

        });
        //Read More and Read Less Click Event binding
        $(document).on("click", ".readMore,.readLess", function() {
            $(this).closest(".addReadMore").toggleClass("showlesscontent showmorecontent");
        });
    }
    $(function() {
        //Calling function after Page Load
        AddReadMore();
    });


  
    </script>
<style>
    .addReadMore.showlesscontent .SecSec,
    .addReadMore.showlesscontent .readLess {
        display: none;
    }

    .addReadMore.showmorecontent .readMore {
        display: none;
    }

    .addReadMore .readMore,
    .addReadMore .readLess {
        font-weight: bold;
        margin-left: 2px;
        color: black;
        cursor: pointer;
    }

    .addReadMoreWrapTxt.showmorecontent .SecSec,
    .addReadMoreWrapTxt.showmorecontent .readLess {
        display: block;
    }
    </style>

 

Link to post
  • Answers 1
  • Created
  • Last Reply

Top Posters For This Question

Top Posters For This Question

1 answer to this question

Recommended Posts

Create an account or sign in to comment

You need to be a member in order to leave a comment


×
×
  • Create New...