What is the best way to insert a "Read More" link following a short snippet of text

I am looking to implement multiple "read more" links to enable users to continue reading after a specified amount of text, such as 1000 words or 2 paragraphs.

<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 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. Etiam tincidunt tellus tristique turpis tincidunt, eget condimentum urna rutrum. Donec maximus consequat dolor, sit amet con...
    </p>
    <p>Etiam posuere tellus mauris, et dignissim nisl rutrum quis. Mauris tincidunt ante sed velit maximus, vel tincidunt leo imperdiet. Morbi nec lacus 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 dignissim efficitur. Proin ex metus, ornare placerat nisi at, porta lobortis turpis.
    </p>
    <p>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. Integer eu dignissim lectus, commodo efficitur metus. Morbi quis justo finibus, interdum sem quis, imperdiet tellus. Curabitur blandit vel magna nec elementum. Vivamus tempor, urna pharetra euismod euismod, elit elit tincidun...
    </p>

Answer №1

A functioning iteration is available here

$(function() {
  $(".show-read-more").each(function() {
    const text = this.textContent;
    const newHtml = text.match(/.{1,300}/g).map((str, i) => `<span class="more-text" hidden>${str} <a href="#" class="read-more">read more...</a></span>`);
    $(this).html(newHtml);
    $(this).find("span").eq(0).show(); // show the first
    $(this).find("span a").last().remove(); // delete the last link
  });
  $(".show-read-more").on("click", ".read-more", function(e) {
    e.preventDefault();
    let $span = $(this).next(".more-text");
    $span = $span.length>0 ? $span : $(this).parent().next(".more-text");
    $span.contents().unwrap();
    $(this).remove();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/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. Pellentesque mattis hendrerit nisi gravida hendrerit. Mauris sagittis tincidunt scelerisque. Vivamus lectus erat, dictum et magna quis, iaculis finibus nisl. Aliquam quis ante odio. Etiam tincidunt tellus tristique turpis tincidunt, eget condimentum urna rutrum...
<p>Etiam posuere tellus mauris, et dignissim nisl rutrum quis. Mauris tincidunt ante sed velit maximus, vel tincidunt leo imperdiet. Morbi nec lacus 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 dignissim efficitur. Proin ex metus, ornare placerat nisi at, porta lobortis turpis.</p>
<p>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. Integer eu dignissim lectus, commodo efficitur metus. Morbi quis justo finibus, interdum sem quis, imperdiet tellus. Curabitur blandit vel magna nec elementum. Vivamus tempor, urna pharetra euismod euismod, elit elit tincidun...
<p>

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

The data in MongoDB is organized using unique identifiers called ObjectId

I am currently working on a MEAN Crud project and encountering some issues. Despite the data being received in the mongodb, it is displaying as an objectId instead of the actual content. You can see this issue in the image below: https://i.stack.imgur.com ...

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

Ensure that the text within the ng-repeat is wrapped in a span element and each

When using ng repeat in span, I encountered a word breaking into a new line. Here is the actual output: https://i.stack.imgur.com/k4c9k.png To style this, I implemented the following CSS: border: 1px solid #ECE9E6; border-radius: 3px; text- ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

MUI: tips for positioning text next to each other on a page

I need assistance aligning numbers and text side by side, similar to the image shown here: https://i.sstatic.net/gXzOM.jpg However, there is a margin to the right of the text(MASTER I 406), causing the numbers to not be in the correct position. Currently, ...

Can you align a row under its corresponding column in Bootstrap?

Hello, I'm facing a dilemma with my layout. I have a grid consisting of 2 Rows and 4 Columns (col-md-8 & col md-4 in each row). The structure is as follows: Within the container Row 1 Column 1 (md-8) Row 1 Column 2 (md-4) [Accordion] Row 2 Colum ...

Issue with Jquery prevents clicking on hyperlinks

I have a table where table rows can be clicked. However, some cells cannot be clicked if they contain hyperlinks. This is because having both actions - one for clicking the table row and another for clicking the hyperlink - can cause confusion. Therefore, ...

Concealed HTML element or generated on-the-fly using JavaScript

What is considered the best practice? I have multiple windows on a page: Auth, Execution Result, and Popups. I can display them in two ways: Create them in pure HTML with CSS, set to display: none, and then fadeIn using jQuery. Create the elements ...

Refreshing the AngularJS application by re-rendering the view without the need for a full reload

I am currently working on an application that heavily utilizes the ng-include directive, and one thing I cannot stand is having to reload the entire application just to see a simple HTML update. I have experimented with manually replaying the XHR in the N ...

Error: Unable to access property 'nTr' as it is not defined

When I invoke the fnSelect function, an error occurs in Chrome: Uncaught TypeError: Cannot read property 'nTr' of undefined This is the code snippet causing the issue: $('#ToolTables_table_id_0, #ToolTables_table_id_1').mousedown(fun ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

When using CKEditor, pressing the Enter key results in the insertion of <br /> tags

Whenever I use ckeditor, I find that pressing enter results in two <br /> tags being inserted. While I want to keep the line break tags, having them appear twice is not ideal. In my config.js file, I have set the configuration for the enter key as f ...

What is the best way to switch content between tabs using ajax and php?

I have organized my content into two tabs and I am switching between the tabs using JavaScript. <div class='tab-container'> <div class='tab-1'> <?php $sql="SELECT * FROM posts WHERE status='tab1'"; echo "<d ...

A guide to utilizing asynchandler within a class in Node.js

I'm currently in the process of converting my routers into a class structure, but I'm facing a challenge when trying to wrap the asyncHandler function inside the class. Can anyone provide guidance on how to achieve this? userController.js const ...

The HTML canvas may sometimes produce inaccuracies in the bytes returned by the getImageData function, a phenomenon known as "

I've come across an issue where the getImageData function of an HTML canvas is returning incorrect byte values. To illustrate, I created a 1x1 pixel image using the following Python code: from PIL import Image import numpy as np a = np.array([[[12, ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

Is there a way to maintain the selected position on the drop-down menu for users?

Whenever I choose an option from the drop-down field in my form, it automatically jumps back to the top of the page. Just to clarify, I have a drop-down menu at the top of the page and several input fields below. Users need to scroll down to reach the dro ...

Tips for Sending Complex Data Types to ASP.NET MVC Controller with Ajax and jQuery

I have encountered an issue where I am receiving null values for the properties of the complex variable (RamarksList) within another complex type (Model). Although the values for Name and Type are displayed correctly, I am facing null values for the prope ...