"Implement a 'Show More/Show Less' Button Functionality for Various Content Using

I'm having trouble implementing a JavaScript solution that adds read more/less buttons to my testimonials. The issue is that it only seems to work for one button and not multiple as I had hoped. Is there a way to modify this code so that it can be used for multiple buttons instead of just one?

function adjustReadMore() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more"; 
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less"; 
    moreText.style.display = "inline";
  }
}
#more {display: none;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h2>Expand & Collapse Testimonials</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="adjustReadMore()" id="myBtn">Read more</button>

<h2>Expand & Collapse Testimonials</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="adjustReadMore()" id="myBtn">Read more</button>

</body>
</html>

Answer №1

It's important to note that IDs must be unique and one-of-a-kind in HTML. If you have multiple elements with the same ID, only the first one will work. Instead, consider using classes and learn how to target elements with event.target in JavaScript for easier manipulation.

  var dots = event.target.previousElementSibling.querySelector(".dots");
  var moreText = event.target.previousElementSibling.querySelector(".more");
  var btnText = event.target;

For more information on targeting elements with events, please refer to this link.

Once you capture the clicked button as an element with the event, you can navigate to other elements by using methods like previousSibling to access the previous paragraph tag and then use querySelector to select the desired class inside it.

function myFunction(event) {
  var dots = event.target.previousElementSibling.querySelector(".dots");
  var moreText = event.target.previousElementSibling.querySelector(".more");
  var btnText = event.target;

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
.more {
  display: none;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>



  <h2>Read More Read Less Button</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
  <button onclick="myFunction(event)" class="myBtn">Read more</button>



  <h2>Read More Read Less Button</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
  <button onclick="myFunction(event)" class="myBtn">Read more</button>

</body>

</html>

Answer №2

To implement this functionality using VanillaJS, you can utilize the following code snippet:

document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll(".lessButton").forEach(element => {
    element.onclick = () => {
        //Add your custom action here   
    }
  });
  
  document.querySelectorAll(".moreButton").forEach(element => {
    element.onclick = () => {
          //Add your custom action here   
    }
  });

});

You have the ability to access attributes like ID and any additional data properties assigned to each button element.

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

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

File is having trouble uploading, could it be related to buffering?

Recently, I've been working on a website for image manipulation using PHP and Imagick. Everything was going smoothly until the function that uploads files to the server suddenly stopped working just 6 hours before the deadline. I suspect that the iss ...

Loading a Threejs model: "The CORS policy has blocked access to XMLHttpRequest from origin 'null' - How can I test this locally? Or should I simply upload it?"

Experimenting with three.js locally on a single HTML page, I am interested in exploring loading and manipulating 3D object files. Here is the code snippet that I am currently using: var loader = new THREE.AMFLoader(); loader.load( '. ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

Avoiding Page Reloads with Ajax while Removing Entries from a Table in Laravel

I am encountering an issue where I can click the button, but it requires a refresh to execute the delete action. Is there something in my ajax code causing this problem and why is it refreshing? I want the button to instantly delete without the need for a ...

"Provide information, then open a new webpage by clicking on a button. Perform various actions with the form by using type

Is there a way to quickly submit form entries to my database and then automatically redirect to a new page? My current situation requires that submitted information is stored in the DB before directing users to a thank you page, all in one seamless click! ...

What is the best method for establishing environment variables across different platforms?

When working with Node scripts on Windows, the format should be like this: "scripts": { "start-docs": "SET NODE_ENV=development&&babel-node ./docs/Server.js" } However, on Linux, the SET command is not used, so it would look like this: "scri ...

pm2 doesn't play well with node dotenv

In my current project, I'm faced with an interesting issue. When running the application locally without pm2, all the environment variables in the .env file are properly recognized using dotenv. However, when deploying the app on a server and using p ...

Using the event object in the onClick handler within React applications

In my React app, I have implemented a feature where clicking on a column heading sorts the data in the table using merge sort algorithm My goal is to pass both the data (an array of objects) and the event object to the sorting function. However, I am faci ...

React - Page Loads with Empty Query Parameters

Seeking assistance with navigation logic in React, I'm encountering an issue that requires some guidance. I have developed a front-end web app using TypeScript, React, and Ionic Framework V5. The app features a standard search box that redirects use ...

Next.js: An absence of response is observed when a high volume of requests is made on a server-side rendering page with

Currently, I am utilizing Next.js along with a custom server (express js) as demonstrated in the GitHub example. For instance, I have a page located at “/post/[id]” that makes use of Next.js dynamic routing. The issue arises when the number of request ...

Deactivate the unclicked button using Vue.JS

I have a scenario with two confirmation buttons - when one button is clicked, it should disable the other button and reveal the content of a specific span element. Initially, both buttons should be enabled until the page loads. Additionally, I want to alt ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Securely Saving JWT Tokens from Auth0 Login in Node.js Express

As a novice in the world of Auth0, I am currently working on integrating it into my regular express web application. My main goal is to secure and validate users before they are able to access certain endpoints. From what I have gathered, this can be achie ...

Guide to retrieving the animation from a VRML file with three.js technology

Is there a way to access the animation within a VRML file using three.js? I've had success with collada files, but I'm not seeing an animation field in the event.content object when it comes to VRML. I've come across this example: https://gi ...

Adding JSON data to a MySQL column in JSON format with the help of NodeJS

I currently have a MySQL table set up with the following specifications: CREATE TABLE `WorkOrders` ( `workorder_id` int(11) NOT NULL AUTO_INCREMENT, `intertype_id` int(11) NOT NULL, `equipment_id` int(11) NOT NULL, `reason_id` int(11) NOT NULL ...

Bootstrap 5 - Achieve automatic column width within a row

In my Bootstrap 5 setup, I have a variety of pages that have different column layouts - sometimes 2 columns, sometimes 3. The template system I'm using dynamically adjusts the layout to accommodate the need for a third column when necessary. <div ...

Navigating through an array in jquery that has been populated by a php script

I am trying to access an array in jQuery that is returned by a PHP script through an Ajax call This is the Ajax call I am making to get the result from the PHP script: $.ajax({ url: "http://localhost/WCPM/index.php/demand/check_demand_ ...

Obtaining a date and time in PHP from a JavaScript array

I am currently working on implementing a JQuery datetime picker and my goal is to save the selected date and time into a PHP variable for storage in a MySQL database. Despite browsing through various examples, none of them seem to be effective in achieving ...

I'm experiencing a strange issue where the timezone offset is being doubled on my computer, yet it is functioning correctly on the UTC

A situation has arisen where the timezone offset on my local server is being duplicated by the server while creating a new event in my app. For every event created by a user, the client-side scripting computes and adds the time zone offset to the input be ...