What is the best way to create a "read-more" button for multiple text sections?

I have a collection of unique artwork displayed on my website, each accompanied by a brief description.

<div>
    <h2>Emotions in Motion</h2>
    <p>
        This piece is a captivating blend of vibrant colors and intricate details that beautifully captures the essence of human emotion. The artist's profound message about the metamorphosis of individuals is skillfully conveyed through this dynamic work of art.
        <span id="text">
            <br />
            "Emotions in Motion" is a powerful reflection of humanity, showcasing a range of emotions from joy to sorrow. It conveys raw emotion and invites viewers to interpret its meaning based on their own experiences. This post-modernist masterpiece demands attention and resonates with viewers on a personal level.
            <br />
           The contrast between chaos and harmony in this artwork creates a thought-provoking narrative that speaks to the complexity of existence. As you gaze upon it, you may find yourself discovering new facets of your own life reflected back at you.
        </span>
    </p>
    <button id="toggle" class="astext">Read More</button>
</div>
<div>
    <h2>Beyond Reality</h2>
    <p>
        "Beyond Reality" is an emotional journey that transcends the boundaries of imagination. This deeply reflective piece challenges perceptions and inspires introspection. The artist's intent to evoke self-realization and acceptance is evident in every brushstroke.
        <span id="text">
            <br />
            At its core, "Beyond Reality" is a harmonious blend of supernatural elements and earthly beauty. It offers a glimpse into the artist's vision and their intimate connection to the world around them. Through this artwork, viewers can explore themes of identity, transformation, and the human experience.
            <br />
            Delve deeper into "Beyond Reality" to uncover hidden layers of meaning and symbolism. Despite its chaotic appearance, this piece ultimately conveys a sense of balance and unity, inviting contemplation and sparking dialogue.
        </span>
    </p>
    <button id="toggle" class="astext">Read More</button>
</div>
<div>
    <p>January 14<sup>th</sup>, 2021</p>
    <img data-src="./images/portfolio/5524E4534A898F56064C481CD305C703.webp" class="lazyload" alt="my image" />
</div>

The additional text content is initially hidden using CSS properties #text {display: none;}

In order to reveal the hidden text when the corresponding button is clicked, JavaScript/jquery code is utilized as follows:

$(document).ready(function() {
  $("#toggle").click(function() {
    var elem = $("#toggle").text();
    if (elem == "Read More") {
      //Show more text when button is in 'Read More' state
      $("#toggle").text("Read Less");
      $("#text").slideDown();
    } else {
      //Hide text when button is in 'Read Less' state
      $("#toggle").text("Read More");
      $("#text").slideUp();
    }
  });
});

Is there a way to streamline the script to handle multiple buttons and associated text sections dynamically?

Answer №1

First, it is recommended to use classes instead of IDs in this situation as having multiple elements with the same ID can cause issues. Utilize jQuery's $(this) along with sibling and children selectors to achieve the desired functionality. By selecting $(this), you target only the element that was clicked, while siblings/children will focus on text elements directly associated with that button within the same div. For a live demo, check out this Codepen.

HTML:

<div>
    <h2>I still get butterflies</h2>
    <p>
        A virtuoso display of personality. A sophisticated layered piece that depicts dynamism and vibrancy while also betraying the turmoil and tranquility of humanity. The artist’s ode to the enduring Metamorphosis of an individual and so
        much more.
        <span class="text">
            <br />
            The artist’s personality is on full display. A breathtakingly beautiful piece; full of energy, light, sorrow, and pain. The artist’s vision will shake you to the very core. This hauntingly post-modernist piece is an exercise in
            raw emotion on canvas; that demands the full attention of the viewer. It is a raw un-tempered glimpse into the fabric of humanity. The vibrancy of colors harmoniously interact with the chaotic themes on display. This artwork
            pulls you in, what message you see in it, what themes you feel the artwork depict are entirely up to you. It will touch everyone differently. You and your guest will see a part of you depicted on the painting, a facet of your
            life laid bare.
            <br />
            &quot;I still get butterflies&quot; is a fascinating portrayal of humanity. The dance of colors, the vibrant display of personality and the chaotic themes on display perfectly gel together to depict the elegance and the reality
            of existence.
        </span>
    </p>
    <button class="toggle astext">Read More</button>
</div>

<div>
    <h2>To levitate</h2>
    <p>
        &quot;To levitate&quot; is a thoughtful, emotional piece that transcends the fabric of reality. This piece appeals directly to the senses, beneath the incessant and formidable dance of colors is a rapturous delight. Ecstasy, so
        profound, so pure that it borders on angelic transformation.
        <span class="text">
            <br />
            &quot;To levitate&quot; is at its heart a deeply disquieting and disturbing display of strange nature that is at once entirely realistic and yet almost supernatural. It conveys a message of self-realization and self-acceptance:
            to break free from the chaos of life. The artist portrays a dazzling song that is beautifully pure. &quot;To levitate&quot; is a majestic creation of colors. It betrays the indefinable aroma of the artist&apos;s sincerity to
            their vision and intercourse with reality. The message of the piece transcends reality, borders on the supernatural, yet within that artistic expression is perhaps the most human message of all.
            <br />
             quot;To levitate&quot; is a deeply feverish piece. At first glance the piece conveys a sense of chaos; it blends the supernatural with reality, but beneath all that chaos lies the harmony of colors, the artist&apos;s intention,
            and a beautifully sublime message.
        </span>
    </p>
    <button class="toggle astext">Read More</button>
</div>
<div>
    <p>January 14<sup>th</sup>, 2021</p>
    <img data-src="./images/portfolio/5524E4534A898F56064C481CD305C703.webp" class="lazyload" alt="my image" />
</div>

JS:

$(document).ready(function() {
  
  
  $(".toggle").click(function() {
    var elem = $(this).text();
    
    if (elem == "Read More") {
      //Perform actions when btn is in read more state
      $(this).text("Read Less");
      $(this).siblings().children('.text').slideDown();
    } else {
      //Carry out actions when btn is in read less state
      $(this).text("Read More");
      $(this).siblings().children('.text').slideUp();
    }
  });
});

Answer №2

Seems like you already have jQuery integrated into your project. Have you thought about utilizing the toggle() method specifically designed for situations like this?

https://www.example.com/jquery-toggle-method

$("#toggleButton").click(function(){
  $("#content").toggle();
});

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

Update the link to a KML file used by Google Maps when a button is clicked

On the initial page load, I want to showcase an 8 Day Average KML file on Google Maps. However, users should have the option to click on the "1 Day" and "3 Day" buttons to switch the reference in Google Maps from the "8 Day" file. The aim is to design a s ...

Export the Excel file with hyperlinks to HTML format so that they can be easily opened in a file explorer instead of a web browser

I've got an excel spreadsheet that contains links to local folders. In order to optimize its compatibility with various devices, I convert it to HTML format. Everything seems to be working smoothly, except for one minor issue - when clicking on the li ...

increasing the size of a particular text box above the rest

Just starting out with bootstrap and trying to figure out how to make one text box larger than the others. See my code below: <div class="row"> <div class="col-md-2"> <mat-form-field > <input matInput pla ...

Creating a 3-column div with varying sizes of text in another div at the center position

I am attempting to create a 3-column layout using only DIVs, but I am facing some challenges. If I were to use tables in the traditional HTML 4 way, I could achieve this: <div style="width:100%"> <table width="50%" align="center"> ...

What is the process for updating npm on a Windows operating system?

Seeking advice on upgrading my npm version, I attempted Option 3 for Windows as outlined in the npm documentation. However, upon installation, I received a message stating that npm.exe already exists in the nodejs folder. Despite trying to overwrite it u ...

Tips for dividing the rows within an array using the match() function?

Within my matrix are arrays of rows. let matrix=[['hello'],['world']]; I am looking to duplicate each row within the matrix. matrix=matrix.map(x=>String(x).repeat(2)).map(x=>x.match(new RegExp??)) The desired outcome should be [ ...

changing date formats using jQuery

I need to extract a date from an h3 tag and convert it to a different date using some functionality in my code behind files. How can I achieve this with jQuery? HTML <div id="firstweekwrapper" class="weekcontainer"> <div ...

Tips for making sure all images are fully loaded before I use them on my HTML canvas

I have a challenge where I need to draw multiple images on an HTML canvas using JavaScript context.drawImage(Im1 ,205,18,184,38); To ensure that each image loads properly, I have to use a specific code structure which limits my ability to draw with it v ...

Ways to link a single image to four different div elements

I currently have a div structured like this: <div class="panel" style="width: 100%; height: 40px; "> <asp:Panel runat="server" ID="Panel1" HorizontalAlign="Center" > <asp:Image id="Image2" runat="server"src="../../_ ...

``What is the best way to include a JavaScript jQuery variable value within a PHP array

Let's consider the following scenario: var folderName = jQuery.trim($('#dirname').val()); var parentFolder = jQuery.trim($('#parent').val()); var dynamicUrl = '<?=$this->url(array('controller'=>'index ...

Exploring the World of Node.js Event Handling in JavaScript

After reviewing the provided code snippet: binaryServer = BinaryServer({port: 9001}); binaryServer.on('connection', function(client) { console.log("new connection"); client.on('stream', function(stream, meta) { console.log(& ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

What is the best way to display the names of students whose grade exceeds 70% using JavaScript?

I am currently utilizing the json-rule-engine library, which can be found at https://www.npmjs.com/package/json-rules-engine. In my scenario, I have a list of students with their names and corresponding percentages. Additionally, there is a specific busine ...

PHP displays the array returned by Ajax as "[object Object],[object Object]"

When working with Jquery, I am creating two arrays - one embedded inside the other. Here is an example of what it looks like: arrayOne = [{name:'a',value:1}, {name:'b',value:2}] var arrayTwo = [{name:'foo',value:'blah&ap ...

Missing post data in jQuery ajax calls for Windows Phone 7

Currently, I am in the process of developing an application for Windows Phone 7 using PhoneGap. Within this application, I am making jQuery AJAX calls to send login POST data to a remote script. Upon sending these login credentials in POST data, the respo ...

jQuery call not proceeding with `$.ajax` request

When making an ajax call with jQuery, I need to pass different ajax options based on the result of an if/else condition. This is how I attempted it: var url = 'form_submission.php'; if (imgAttached) { var params = $form.serializeArray(), ...

attempting to transfer website form data to WhatsApp platform

I have developed a website where users can fill out a form and submit their data. I want to send this form data to WhatsApp, so I tried using Twilio. However, Twilio is only free for the first day. Is there any other software that allows me to send form da ...

I encountered a crash in my app because of an error in my Node.js backend code that was posting the accessories and slug into the database

My node.js backend code is responsible for adding the accessory and slug to the database, but I am encountering app crashes. const express=require('express'); const Category = require("../models/Category"); const slugify=require('s ...

Struggling to fetch the last and first name from a document in Firestore using VueJs

https://i.sstatic.net/IdZGi.pngWhen trying to retrieve the last name and first name from a document stored upon signup with a field displayName, I encountered an issue. Despite having a common key as displayName, which should allow me to fetch this informa ...

Downloading files in AngularJS can sometimes be problematic when the file name contains spaces

I am currently using AngularJS to download files by sending GET requests. The file I am trying to download is named flower-red.jpg. Here is an example of my request: GET http://localhost:8080/aml/downloadDoc/852410507V/flower-red.jpg The download is succ ...