How to Create Multiple "Read More" Buttons Using HTML, CSS, and JavaScript

 In this tutorial, we’ll create multiple "Read More" buttons that reveal hidden content when clicked. This is a common feature in blogs and articles to keep the initial content concise and provide additional details on demand.



Step 1: HTML

First, we need the HTML structure. Each section contains some initial text, a hidden text section, and a "Read More" button. Now I create only one section, u can add more section with that same class name

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Read more button</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <main>
        <section>
           <div class="read-more">
            <div class="container">
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                    In fugiat et maiores dolore, vel error similique illo saepe,
                    quaerat vero deserunt. <span class="more-text">Hic odit culpa
                    sed expedita est vero sapiente ipsa.
                    Sit, maxime, praesentium suscipit deleniti optio dolorem molestias
                    cum repellendus consequuntur atque aliquam aperiam distinctio esse
                    maiores nesciunt!</span></p>
                <button class="read-more-btn">Read more</button>
            </div>
           </div>
        </section>
    </main>

    <script src="app.js"></script>
</body>
</html>


Explanation:

  1. <!DOCTYPE html>:
    • Declares the document type and version of HTML being used. In this case, it is HTML5.
  2. <html lang="en">:
    • The root element of the HTML document. The lang attribute specifies the language of the document (English).
  3. <head>:
    • Contains meta-information about the document, such as its title, character set, and linked resources (e.g., CSS files).
  4. <meta charset="UTF-8">:
    • Sets the character encoding for the document to UTF-8, ensuring that the text is correctly displayed.
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">:
    • Sets the viewport settings, which are crucial for responsive web design. It ensures that the layout is adjusted based on the device's width.
  6. <title>Read More Buttons</title>:
    • Specifies the title of the web page, which appears in the browser tab.
  7. <link rel="stylesheet" href="styles.css">:
    • Links an external CSS file (styles.css) that contains the styles for the page.
  8. <body>:
    • Contains the content of the HTML document that is visible to the users.
  9. <div class="content-container">:
    • A container div element with the class content-container. It groups the text and button elements.
  10. <p class="content">This is some content. <span class="more-text">Here is some additional content that is initially hidden.</span></p>:
    • A paragraph element with the class content. It contains some initial visible text.
    • Inside the paragraph, there is a span element with the class more-text. This span contains the additional text that will be toggled.
  11. <button class="read-more-btn">Read More</button>:
    • A button element with the class read-more-btn. This button will toggle the visibility of the additional text.
  12. <script src="scripts.js"></script>:
    • Links an external JavaScript file (scripts.js) that contains the script for toggling the text visibility.


Step 2: CSS 

The CSS styles the content and the buttons. Here's the full CSS code with explanations:

body{
    background-color: #000;
    padding: 2rem;
}
.container{
    background-color: #fff;
    padding: 20px;
    width: 400px;
    border-radius: 5px;
    line-height: 23px;
}
.read-more-btn{
    border: none;
    outline: none;
    background-color: #ffb703;
    padding: 10px 15px;
    margin-top: 20px;
    border-radius: 5px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
}
.more-text{
    display: none;
}


Explanation:

  1. body { background-color: #000; padding: 2rem }:
    • Applies the background color to white and add some padding to entire body
  2. .container { .... }:
    • This CSS rule styles elements with the class container to have a white background, 20px padding, 400px width, 5px rounded corners, and a line height of 23px.
  3. .more-text { display: none;}:
    • .more-text: Targets the elements with the class more-text.
    • display: none;: Hides the element by default.
  4. .read-more-btn { ... }:
    • Targets the elements with the class read-more-btn and applies various styles to the buttons:
      • background-color: #ffb703;: Sets the background color to a shade of orange.
      • color: white;: Sets the text color to white.
      • border: none;: Removes the border.
      • padding: 10px 15px;: Adds padding inside the button (10px top and bottom, 15px left and right).
      • font-size: 16px;: Sets the font size to 16px.
      • margin-top: 20px;: Adds a 20px margin to the top of the button.
      • cursor: pointer;: Changes the cursor to a pointer when hovering over the button, indicating it's clickable.
      • border-radius: 5px;: Rounds the corners of the button with a 5px radius.


Step 3: JavaScript (scripts.js)

Finally, we add the JavaScript to make the buttons functional.


document.addEventListener('DOMContentLoaded', function() {
    // Select all elements with the class 'read-more-btn'
    const buttons = document.querySelectorAll('.read-more-btn');

    // Loop through each button
    buttons.forEach(button => {
        // Add a click event listener to each button
        button.addEventListener('click', function() {
            // Find the hidden text related to this button
            const content = this.previousElementSibling.querySelector('.more-text');

            // Toggle the visibility of the hidden text
            if (content.style.display === 'none' || content.style.display === '') {
                content.style.display = 'inline'; // Show the hidden text
                this.textContent = 'Read Less'; // Change button text to 'Read Less'
            } else {
                content.style.display = 'none'; // Hide the text again
                this.textContent = 'Read More'; // Change button text back to 'Read More'
            }
        });
    });
});


Explanation:

  1. document.addEventListener('DOMContentLoaded', function() {...}):
    • document: Refers to the HTML document.
    • addEventListener('DOMContentLoaded', function() {...}): Adds an event listener to the document that listens for the 'DOMContentLoaded' event. This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
    • function() {...}: The function that will be executed once the 'DOMContentLoaded' event fires.
  2. const buttons = document.querySelectorAll('.read-more-btn');:
    • const: Declares a variable that cannot be reassigned.
    • buttons: The name of the variable that will store the result.
    • document.querySelectorAll('.read-more-btn'): Uses the querySelectorAll method to select all elements in the document with the class read-more-btn. This returns a NodeList (similar to an array) of all matching elements.
  3. buttons.forEach(button => {...}):
    • buttons: Refers to the NodeList of button elements selected previously.
    • forEach(button => {...}): Iterates over each element in the NodeList. The forEach method takes a callback function that is executed once for each element in the array. In this case, button is the current element being processed in the loop.
    • button => {...}: Arrow function that takes the current button element as its parameter.
  4. button.addEventListener('click', function() {...}):
    • button: Refers to the current button element in the loop.
    • addEventListener('click', function() {...}): Adds a click event listener to the current button element. When the button is clicked, the specified function will be executed.
    • function() {...}: The function that will be executed when the button is clicked.
  5. const content = this.previousElementSibling.querySelector('.more-text');:
    • const: Declares a variable that cannot be reassigned.
    • content: The name of the variable that will store the result.
    • this: Refers to the current button element that was clicked.
    • previousElementSibling: Gets the element immediately before the current button element in the DOM tree. This should be the paragraph (<p>) element that contains the text.
    • querySelector('.more-text'): Selects the first element with the class more-text within the previous sibling element (the paragraph).
  6. if (content.style.display === 'none' || content.style.display === '') {...}:
    • if: Conditional statement that executes the code block inside if the condition evaluates to true.
    • content.style.display: Accesses the display style property of the content element.
    • === 'none': Checks if the display property is set to none, which means the element is hidden.
    • ||: Logical OR operator.
    • === '': Checks if the display property is an empty string, which means no display property is set, and the element is hidden by default due to the initial CSS.
  7. content.style.display = 'inline';:
    • content.style.display: Accesses the display style property of the content element.
    • = 'inline';: Sets the display property to inline, making the hidden text visible.
  8. this.textContent = 'Read Less';:
    • this: Refers to the current button element that was clicked.
    • textContent: Gets or sets the text content of the button element.
    • = 'Read Less';: Sets the text content of the button to 'Read Less'.
  9. else {...}:
    • else: Executes the code block inside if the if condition is false.
  10. content.style.display = 'none';:
    • content.style.display: Accesses the display style property of the content element.
    • = 'none';: Sets the display property to none, hiding the text again.
  11. this.textContent = 'Read More';:
    • this: Refers to the current button element that was clicked.
    • textContent: Gets or sets the text content of the button element.
    • = 'Read More';: Sets the text content of the button to 'Read More'.

Download the file here


Previous Post Next Post