Implementing ‘Read More’ and ‘Read Less’ Functionality with JavaScript

Enhancing User Experience: Implementing ‘Read More’ and ‘Read Less’ Functionality with JavaScript

In the world of web content, sometimes less is more. Long paragraphs of text can be overwhelming for readers, and it’s essential to strike a balance between providing information and maintaining a clean, user-friendly design. One effective solution is the “Read More” feature, which allows users to expand and collapse text as needed.

In this blog post, we’ll guide you through a simple HTML, CSS, and JavaScript code snippet that enables you to add a “Read More” button to any text content on your website. Whether it’s articles, product descriptions, or any other textual information, this code can make your web pages more user-friendly and engaging.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Implementing "Read More" and "Read Less" Feature for Text Content</title>

    <!-- Add your CSS styles here -->
    <style>
body{
	background-color: #f9f9f9;
	font-family: Lora, serif;
}
.content-item{
	background-color: #ffffff;
	text-align: center;
	font-size: 18px;
	width: 500px;
	padding: 20px;
	box-shadow: 2px 2px 4px rgba(0,0,0,0.25);
	margin: 0 auto;
}
.content-item .read-more {
            display: none;
        }

        .content-item .read-more-link,
        .content-item .read-less-link{
            display: block;
            text-align: center;
            font-weight: 700;
            color: #999999;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <!-- Example text content with the "Read More" feature -->
    <div class="content-item">
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Sed ullamcorper, nulla a convallis varius, odio urna facilisis enim,
            ac consectetur ipsum nisi in libero. Curabitur hendrerit, elit quis
            congue consequat, lectus neque ultrices odio, nec sollicitudin justo
            quam ac velit. <strong>Vestibulum ullamcorper bibendum turpis</strong>, non
            <b>faucibus dui fermentum a.</b> Nunc eget tortor rhoncus, dignissim mi nec,
            sagittis metus. Duis euismod sapien a nunc facilisis, sed suscipit erat
            dapibus.
        </p>
    </div>

    <!-- Include your JavaScript code here -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const contentItems = document.querySelectorAll(".content-item");

            contentItems.forEach(function(item) {
                const content = item.querySelector("p");
                const textContent = content.innerHTML;
                const maxCharacters = 150; // Adjust this to your desired character limit

                function truncateText(text, maxCharacters) {
                    if (text.length <= maxCharacters) {
                        return text;
                    }
                    const truncatedText = text.slice(0, maxCharacters);
                    return truncatedText;
                }

                const truncatedHtml = truncateText(textContent, maxCharacters);
                const remainingHtml = textContent.slice(truncatedHtml.length).trim();

                if (remainingHtml.length > 0) {
                    content.innerHTML = truncatedHtml;
                    content.innerHTML += `<span class="read-more">${remainingHtml}</span>`;
                    content.innerHTML += ' <a href="#" class="read-more-link">Read More</a>';
                    content.innerHTML += ' <a href="#" class="read-less-link" style="display: none;">Read Less</a>'; // Added Read Less link

                    const readMoreLink = content.querySelector(".read-more-link");
                    const readLessLink = content.querySelector(".read-less-link");
                    const readMoreText = content.querySelector(".read-more");

                    readMoreLink.addEventListener("click", function(e) {
                        e.preventDefault();
                        readMoreText.style.display = "inline";
                        readMoreLink.style.display = "none";
                        readLessLink.style.display = "inline"; // Show the Read Less link
                    });

                    readLessLink.addEventListener("click", function(e) {
                        e.preventDefault();
                        readMoreText.style.display = "none"; // Hide the extra text
                        readMoreLink.style.display = "inline"; // Show the Read More link
                        readLessLink.style.display = "none"; // Hide the Read Less link
                    });
                }
            });
        });
    </script>
</body>
</html>

Understanding the Code

1. HTML Structure

To start, you need to create a structure in your HTML to hold the text content you want to make expandable:

<div class="content-item">
    <p>
        <!-- Your text content goes here -->
    </p>
</div>

Each <div class="content-item"> represents one piece of content. You can have multiple sections of text by duplicating this structure.

2. Styling with CSS

Next, let’s examine the CSS styles for styling the content and the “Read More” feature:

<style>
body{
	background-color: #f9f9f9;
	font-family: Lora, serif;
}
.content-item{
	background-color: #ffffff;
	text-align: center;
	font-size: 18px;
	width: 500px;
	padding: 20px;
	box-shadow: 2px 2px 4px rgba(0,0,0,0.25);
	margin: 0 auto;
}
.content-item .read-more {
            display: none;
        }

        .content-item .read-more-link,
        .content-item .read-less-link{
            display: block;
            text-align: center;
            font-weight: 700;
            color: #999999;
            margin-top: 10px;
        }
</style>

These CSS rules define the initial appearance of the content and the “Read More” links. You can customize these styles to match your website’s design.

3. JavaScript for “Read More”

The JavaScript code provided in the snippet is responsible for implementing the “Read More” feature. Here’s a closer look at each part:

Document Loading Event

document.addEventListener("DOMContentLoaded", function() {
    // ...
});

This event listener ensures that the JavaScript code runs after the HTML document has been fully loaded. This is important to make sure the code can access and manipulate the DOM elements correctly.

Selecting Content Items

const contentItems = document.querySelectorAll(".content-item");

This line selects all elements with the class .content-item. These elements are the containers for your text content. If you have multiple sections of text that you want to make expandable, each should be enclosed in a <div class="content-item">.

Extracting and Truncating Text

contentItems.forEach(function(item) {
    const content = item.querySelector("p");
    const textContent = content.innerHTML;
    const maxCharacters = 150; // Adjust this to your desired character limit

    function truncateText(text, maxCharacters) {
        if (text.length <= maxCharacters) {
            return text;
        }
        const truncatedText = text.slice(0, maxCharacters);
        return truncatedText;
    }

    const truncatedHtml = truncateText(textContent, maxCharacters);
    const remainingHtml = textContent.slice(truncatedHtml.length).trim();
    // ...
});

For each .content-item, this code extracts the text content from the <p> element within it. It also sets a maxCharacters variable to determine the character limit for truncation.

The truncateText function is then used to truncate the text content if it exceeds the character limit. It checks if the text length is less than or equal to the limit and returns either the full text or the truncated version.

Creating “Read More” Elements

if (remainingHtml.length > 0) {
    content.innerHTML = truncatedHtml;
    content.innerHTML += `<span class="read-more">${remainingHtml}</span>`;
    content.innerHTML += ' <a href="#" class="read-more-link">Read More</a>';
    content.innerHTML += ' <a href="#" class="read-less-link" style="display: none;">Read Less</a>'; // Added Read Less link
    // ...
}

If the text content is truncated (i.e., remainingHtml.length > 0), the code proceeds to create the “Read More” feature. It replaces the content of the <p> element with the truncated HTML, adds a <span> to hold the remaining text (initially hidden), and includes “Read More” and “Read Less” links.

Event Listeners for “Read More” and “Read Less”

const readMoreLink = content.querySelector(".read-more-link");
const readLessLink = content.querySelector(".read-less-link");
const readMoreText = content.querySelector(".read-more");

readMoreLink.addEventListener("click", function(e) {
    e.preventDefault();
    readMoreText.style.display = "inline";
    readMoreLink.style.display = "none";
    readLessLink.style.display = "inline"; // Show the Read Less link
});

readLessLink.addEventListener("click", function(e) {
    e.preventDefault();
    readMoreText.style.display = "none"; // Hide the extra text
    readMoreLink.style.display = "inline"; // Show the Read More link
    readLessLink.style.display = "none"; // Hide the Read Less link
});

These event listeners are crucial for enabling the “Read More” and “Read Less” functionality. When the “Read More” link is clicked, it prevents the default link behavior, displays the hidden text (readMoreText), hides the “Read More” link, and shows the “Read Less” link.

Conversely, when the “Read Less” link is clicked, it hides the extra text, shows the “Read More” link again, and hides the “Read Less” link.

Customization Tips

  1. Multiple Instances: You can apply this “Read More” feature to multiple sections of text on the same page by repeating the <div class="content-item"> structure for each section. Each section will operate independently, allowing users to expand and collapse text in different parts of your webpage.
  2. Character Limit: Adjust the maxCharacters variable to suit the specific character limit that makes sense for your content. For longer articles, you might want to set a higher limit, while for shorter pieces, a lower limit might be more appropriate.
  3. Styling: Customize the CSS styles to match your website’s branding and design. You can change the color, font size, and other styling properties to ensure a seamless integration with your site’s aesthetics.
  4. Link Text: Modify the “Read More” and “Read Less” link text to better suit your website’s language and the context of your content. For example, you can use “Show More” and “Show Less” instead of “Read More” and “Read Less” if it fits your content better.
  5. HTML Structure: While the code uses a <p> element for text content, you can adapt it to other HTML elements that contain your text, such as <div> or <article>. Just make sure to adjust the code accordingly.
  6. Accessibility: Ensure that the “Read More” feature is accessible to all users, including those with disabilities. Properly label the links, and consider using ARIA attributes to enhance accessibility.

Testing and User Experience

Before deploying this feature on your live website, it’s crucial to thoroughly test it across different browsers and devices to ensure a consistent and user-friendly experience. Check that the text truncation, link functionality, and styling work as expected.

Consider seeking feedback from users or conducting usability testing to gather insights into how well the “Read More” feature enhances the readability of your content.

Performance Considerations

While the “Read More” feature is a valuable addition to enhance user experience, be mindful of performance considerations, especially if you have many instances of it on a single page with large text content. Excessive use of JavaScript DOM manipulation can impact page load times. Always aim for a balance between functionality and performance.

Conclusion

Adding a “Read More” feature to your text content can significantly improve the user experience on your website. It enables you to provide a concise presentation of information while still offering the option to explore more details when desired. This code snippet provides you with a flexible and reusable tool to enhance the readability and user-friendliness of your web pages.

By following the customization tips and best practices mentioned above, you can tailor this feature to your specific needs and ensure it seamlessly integrates with your website’s design and content. Remember to prioritize accessibility and usability to create a positive browsing experience for all users.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *