简体   繁体   中英

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

i want add "show more" and "show less" functionality after 100 words in the artice description :in this page http://devo.cutwatches.com/en/component/spsimpleportfolio/item/3-powerfull

i have used this cod but it dont work , it give Uncaught TypeError: $ is not a function

        <p class="show-read-more">
        <?php echo $this->item->description; ?>  </p>

and

  <script type="text/javascript">
$(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 type="text/css">
    .show-read-more .more-text{
    display: none;
}

`

i have tried it with css but it not work

how can i fix it please ?

Your html should be like this

<html>
  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  </head>
  <body>

  // Body

  <script type="text/javascript">
    $(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>

 </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM