The show more/show less link for a long jQuery paragraph is malfunctioning

I encountered an issue while coding where the "read more" link works correctly, but the "show less" link does not. Despite my efforts, I cannot seem to identify the error. Within this code snippet, there is an anchor tag with class="show-less" that I am using to hide the span element with class="spanTxt". However, for some reason, it is not concealing the span element properly. I'm puzzled by this situation - if I can use display:inline in the read more link, why isn't the display:none working as intended in the show less link?

Any assistance would be greatly appreciated :)

        <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>jQuery Add Read More Link</title>
    <script type="text/javascript"   src="http://code.jquery.com/jquery.min.js"></script>
    <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).replaceWith('<p class="show-read-more">'+newStr+'<a class="read-more" href="#">read more...</a>'+'<span id="hoja" class="spanTxt" style="display:none">'+removedStr+'</span>'+'</p>');
            }
        });
        
        $(".read-more").click(function(){
            $(".spanTxt").css("display","inline");
            $(".show-read-more").append('<a href="#" class="show-less">show   less...</a>');
            $(this).hide();
        });

        $(".show-less").click(function(){
            $(".spanTxt").css("display","none");

        });
    });
    </script>
    <style type="text/css">

    </style>
    </head>
    <body>
          <p class="show-read-more">Ut auctor velit sed consectetur rhoncus. Nunc 
            dictum facilisis felis nec facilisis. Integer nec justo vitae orci cursus 
            fermentum. Fusce semper, mi non tempus congue, velit leo efficitur quam, 
            laoreet venenatis libero felis et lacus. Pellentesque mattis hendrerit 
            nisi gravida hendrerit. Mauris sagittis tincidunt scelerisque. Vivamus lectus 
            erat, dictum et magna quis, iaculis finibus nisl. Aliquam quis ante odio. Eti
            am tincidunt tellus tristique turpis tincidunt, eget condimentum urna rutrum. 
            Donec maximus consequat dolor, sit amet condimentum ipsum gravida ac. Etiam p
            osuere tellus mauris, et dignissim nisl rutrum quis. Mauris tincidunt ante 
            sed velit maximus, vel tincidunt leo imperdiet. Morbi nec lac
            us et metus semper porttitor. Sed pellentesque ex at 
            pellentesque scelerisque. Aliquam placerat gravida tortor, in fermentum ante
            commodo quis. Etiam vehicula elementum quam. Aliquam eu augue eu lacus digni
            ssim efficitur. Proin ex metus, ornare placerat nisi at, porta lobortis turpi
            s. Praesent euismod nec nulla ultrices maximus. Vivamus imperdiet quam ac
            lobortis cursus. Nam dapibus ullamcorper magna vehicula aliquam. Vivamus 
            hendrerit molestie neque. Ut interdum diam a purus ultrices facilisis. 
            Suspendisse molestie tempor dolor, sed tristique enim sagittis vitae. I
            nteger eu dignissim lectus, commodo eff
            icitur metus. Morbi quis justo finibus, interdum sem quis, imperdiet tellus
            andit vel magna nec elementum. Vivamus tempor, urna pharetra euismod euis
            mod, elit elit tincidunt sem, ut consectetur arcu massa non diam.
            Etiam scelerisque nisi magna. Nulla facilisi. 
            Sed pharetra nunc lectus, in maximus dolor ornare sit amet.</p>


    </body>
    </html>                                     

Answer №1

There are multiple issues present in the code that need to be addressed. Some of them prevent the code from working altogether, while others only allow it to work for the first p.show-read-more element.

To resolve these issues, follow the fix outlined below:

$(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);
      var newP = $('<p class="show-read-more">'+newStr+'<a class="read-more" href="#">read more...</a>'+'<span id="hoja" class="spanTxt" style="display:none">'+removedStr+'</span>'+'</p>')
      newP.append($('<a href="#" class="show-less">show   less...</a>').hide())
      $(this).replaceWith(newP);
    }
  });
  $(".read-more").click(function(){
    $(this).parent('.show-read-more').find('.spanTxt').css("display","inline");
    $(this).parent('.show-read-more').find('.show-less').show();
    $(this).hide();
  });
  $(document).on('click', '.show-less', function(){
    $(this).parent('.show-read-more').find('.read-more').show();
    $(this).parent('.show-read-more').find(".spanTxt").hide();
    $(this).hide();
  });
});
<script type="text/javascript"   src="http://code.jquery.com/jquery.min.js"></script>
<p class="show-read-more">Ut auctor velit sed consectetur rhoncus. Nunc 
  dictum facilisis felis nec facilisis. Integer nec justo vitae orci cursus 
  fermentum. Fusce semper, mi non tempus congue, velit leo efficitur quam, 
  laoreet venenatis libero felis et lacus... (content continues)

Answer №2

Don't forget to include a closing bracket for the $(document).ready(function(){ in your script. Failing to do so may result in JavaScript errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to displaying query results separately on a single webpage

On my page, I have two distinct sections: 1) A list of regular questions; 2) A top-voted list of popular questions Both of these sections rely on calls to the same backend API, with the only difference being an additional parameter passed for the popular ...

Issues with the Jquery feedback plugin's functionality are currently preventing it

I wanted to incorporate a feedback feature into my web application. To do this, I searched on Google and found a suitable jQuery plugin. I followed the documentation provided by the plugin, including the library in my HTML file, and then wrote the code as ...

Error: Could not locate local grunt on Windows 7 Professional

When attempting to initiate grunt, an error message is displayed: c:\repositories\kunde_1\themes-projekt_1\projekt_1-responsive\source>grunt grunt-cli: The grunt command line interface. (v0.1.13) Fatal error: Unable to find lo ...

Having trouble installing $ npm i mini-css-extract-plugin. Any ideas on what might be causing the issue?

There seems to be an error in my setup. I am using Visual Studio Code with gitBash. $ npm i mini-css-extract-plugin npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-p ...

Is there a way to retrieve the textFrame where the cursor is currently located?

While inputting text into a frame, I am looking to execute a script. I want this script to target the specific text frame where my cursor is located. How can I reference this particular textFrame using Javascript? ...

Can you provide me with information on how to retrieve data from a Yahoo Finance JSON file using Node.js?

I have created a simple request function to fetch JSON data from the Yahoo Finance API, but I am encountering difficulties in extracting information from the JSON response. Here is my code: var request = require("request"); var stock_url = "http://finan ...

Tips on concealing and deactivating the fullscreen option in flowplayer

Could someone please assist me in resolving this issue? I've been attempting to hide the fullscreen button from the flowplayer, but so far, I haven't found a solution. Below is my JavaScript code: <script> $f("player", "flowplayer/flowpla ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

The value within the style.setProperty function does not get applied

I have a progress bar that dynamically increases based on user input: <div class="progressBarContainer percentBar"> <div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar">< ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

Table designed using the Flexbox layout model

I am looking to create a table with multiple columns that can handle dynamic data. The challenge is that using the base <table> element would cause the column width to change when the content changes and I also need the ability to hide columns using ...

Sending a collection of objects from an Ajax call to a WebMethod

My objective is to transfer data from a form to a WebMethod. I aim to fill the UseInfo object with form data and also populate certain properties added to the NewUser class passed through the ajax request. Passing the UserInfo as an input parameter result ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

Tips for automatically closing one sub menu while selecting another sub menu

I am working on a code snippet to manage the menu functionality. My goal is to ensure that when I click to open one submenu, any other currently open submenus should automatically close. ;(function($) { // Ensuring everything is loaded properly $ ...

Encode data in JSON format using Javascript and then decode it using PHP

In my coding journey, I decided to create an object using Javascript to pass it as an argument to a PHP script. var pattern = new Object(); pattern['@id'] = ''; pattern['@num'] = ''; pattern.cprop = new Object(); // ...

What is the best way to apply a class to the grandparent div of an element in AngularJS?

Currently, I have a dynamically generated list of tests: <script id="TestsTemplate" type="text/ng-template"> <article class="tests-main"> <section class="tests"> <div class="test" ng-repeat="test in ...

Encountering the error of receiving "$ undefined," despite making a reference to the library

I have included the JQuery library in the following way: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> Despite trying to download the library and include it locally in my project, I ...

Utilizing CSS to position an image at both the top and bottom of a webpage

I have been struggling to find a solution to this particular issue. My goal is to position an image at both the top and bottom of the page using a background property. I understand that by making the positioning relative, the image will be placed at the bo ...

Issue encountered while attempting to set up react-native project

Whenever I attempt to create a new react-native project using the command: npx react-native init myproject I encounter the following errors: ERESOLVE is overriding peer dependency npm gives me a warning while trying to resolve: [email protected] ...

Unable to retrieve the JSON response sent by the REST API within an HTML page

My ajax function is unable to properly receive the JSON content generated by a REST API. The REST API successfully creates the JSON data, but when passed to my ajax function, it does not work as expected. function loadJsonData(){ var dropDownValue = ...