Tips for updating a button's text when clicked

One feature on my webpage is a "Read More" button that, when clicked, expands to reveal additional information (button not pressed). Here is how it appears once the user has clicked the button (button pressed). Despite my research on Stack Overflow, I have not been able to find a solution. My goal is to change the text on the button from "Read More" to "Read Less" after the user clicks on it.

For reference, here is the JS/CSS/HTML code:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
button.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 14px;
  width: 30%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  left: 0;
  right: 0;
}

button.accordion.active,
button.accordion:hover {
  background-color: #ddd;
}

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<button class="accordion">Read More</button>
<div class="panel">
  This content shows up when the user clicks "Read More"
</div>

Any assistance would be greatly appreciated!

Answer №1

Within the onclick event handler, you are currently checking the status of the "panel" and adjusting the styling correspondingly. In addition to this, you can also modify the .innerText of the button that was clicked. Here is an example:

if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
    this.innerText = "Show More"; // changing text here
} else {
    panel.style.maxHeight = panel.scrollHeight + "px";
    this.innerText = "Show Less"; // modifying text here
}

Answer №2

To update the content, simply modify the innerHTML attribute in the following manner:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
      this.innerHTML = "Show More";
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
      this.innerHTML = "Show Less";
    }
  }
}
button.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 14px;
  width: 30%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  left: 0;
  right: 0;
}

button.accordion.active,
button.accordion:hover {
  background-color: #ddd;
}

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<button class="accordion">Show More</button>
<div class="panel">
  Additional information displayed when the user clicks "Show More"
</div>

Answer №3

To modify the text of the button within the if -- else condition where you are adjusting the appearance of the div, there is no need to set up another test. The if -- else statement is located within the on-click function of the button, allowing you to utilize this to pinpoint the specific button:

var btns = document.getElementsByClassName("btn");
var index;

for (index = 0; index < btns.length; index++) {
  btns[index].onclick = function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.maxHeight) {
      content.style.maxHeight = null;
      this.innerText = "Show More"; // 'this' refers to the button
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
      this.innerText = "Show Less"; // 'this' denotes the button
    }
  }
}
button.btn {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 14px;
  width: 30%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
}

button.btn.active,
button.btn:hover {
  background-color: #ddd;
}

div.content {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<button class="btn">Show More</button>
<div class="content">
  Content displayed upon clicking "Show More"
</div>

Answer №4

Simply switch the innerHTML of your button.

if (panel.style.maxHeight) {

    this.innerHTML = "Show More";
      panel.style.maxHeight = null;
    } else {

    this.innerHTML = "Show Less";
      panel.style.maxHeight = panel.scrollHeight + "px";
    }

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
   if (panel.style.maxHeight) {
    
    this.innerHTML = "Show More";
      panel.style.maxHeight = null;
    } else {
    
    this.innerHTML = "Show Less";
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
button.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 14px;
  width: 30%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  left: 0;
  right: 0;
}

button.accordion.active,
button.accordion:hover {
  background-color: #ddd;
}

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<button class="accordion">Show More</button>
<div class="panel">
  Content displayed when user clicks "Show More"
</div>

Answer №5

Here is the code snippet that will help you accomplish this:

if (box.style.height) {
      box.style.height = null;
      button.textContent = "Show More"; // 'button' here refers to the button element
} else {
      box.style.height = box.scrollHeight + "px";
      button.textContent = "Show Less"; // 'button' here refers to the 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

Revamp your jQuery Ajax call by utilizing the Fetch API

Below is my attempt to convert the following jquery's AJAX call using the fetch function: const sendingData = {...} $.ajax({ url: "/api/data/getuser", type: "GET", data: sendingData , dataType: 'json', ContentType: &a ...

When it comes to HTML and Javascript, there is a distinct contrast between an ajax call and altering the content of an

I am currently working on coding a JavaScript function to allow liking a specific post on Tumblr. I came across this helpful resource for reference. Initially, I attempted using an ajax call instead of modifying the source of an iframe, but unfortunately, ...

Error occurred while attempting to parse JSON on comment system

I've run into some issues with my comments system. Everything was working perfectly yesterday, but today I started getting errors. I'm using json to post comments without reloading the page, but now I'm encountering a "SyntaxError: JSON.pars ...

Is it possible to change individual pixels within a canvas without the need to duplicate the entire buffer?

Is it possible to directly alter individual pixels within a canvas, rather than retrieving the entire buffer using ctx.getImageData and then pasting it back with ctx.putImageData? This is crucial in order to avoid the costly process of copying data every ...

Customizing the parent class of an input in Blazor/Scss: A step-by-step guide

My current set up involves using <label> elements with an <input type=radio> as a child. This enables the label to be clickable and trigger the selection of the corresponding radio input. <div id="content"> <label class="optio ...

Utilizing an ActiveX control embedded within another ActiveX control on a webpage

Struggling with accessing a non IDispatch method in an ActiveX control I created. In my web page, I have two separate Active X objects that were developed by me. The issue arises when I call a method on the first object, which returns an interface pointer ...

What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked. However, there ar ...

CSS3 flip effect on hover and click causing issues

I have successfully implemented a card flip effect using CSS3. The card is flipped using jQuery and CSS CSS .flipped { -webkit-transform: rotateY( 180deg ); -moz-transform: rotateY( 180deg ); -o-transform: rotateY( 180deg ); transfor ...

What is the best way to showcase an unordered list alongside corresponding images, with a paragraph text next to each one?

Hey there, I need a little help with displaying an unordered list correctly. Here's how it should look: Below is the code snippet that needs some fixing: <ul> <li><img src="images/02.jpg" alt="Picture 1"></li> ...

Creating a sidebar with child elements in Vitepress: A beginner's guide

I'm having trouble displaying my folder tree in the sidebar. When I click on a parent element like Group, the children elements are not showing up as expected. https://i.sstatic.net/kdc98.png One strange thing is that the Group elements do not have ...

HTML and Python synchronize perfectly when handling date formatting

Here is a code snippet I am working with: {% for x in fixtures %} <TR style="display:block" onclick="team_visibility('match{{ forloop.counter }}');"> <TD> {{ x.fixturedate }}</TD> ...

Is there a way to reverse the hover effect on div elements?

Let's start by examining the code I've written: HTML: <div class="button_container"> <div class="inner_button"> <a href="#" class="button_text">Button</a> </div> <div class="button_side"> ...

Data binding in Vue.js seems to be malfunctioning

I'm having trouble with my Vue component creation. I've been using v-show to hide certain elements, but it doesn't seem to be working as intended. The goal is to hide an element when clicked from a list by setting element.visible to false i ...

Unable to forward with POST request in Node.js

I have a button on the front end that allows users to update their profile photo using the Cloudinary API. When the button is clicked, a Node.js POST request is sent with the user's data to query the database and update the profile photo URL. The func ...

Enhancing the appearance of unvisited links with background styles

I am endeavoring to incorporate an icon into all unvisited links on a specific Wordpress category page. Below is the CSS code that I am utilizing. It has been placed at the conclusion of my final CSS file. .category-xyzzy .entry-title a:link { background ...

Is there a way to implement jQuery for displaying and hiding DIVs according to checkboxes in a form submitted from a separate page?

How can I achieve the functionality of submitting a form on one page, and then dynamically showing or hiding DIVs on the next page based on the checkboxes that were selected? It's also important for the script to display custom messages depending on w ...

Extracting text from an array within Meteor

I am currently utilizing Meteor along with the ajduke:bootstrap-tagsinput plugin for managing tags on my platform. Check out the ajduke:bootstrap-tagsinput example page here For inserting tags as arrays, I am using the True Multiple Value feature mention ...

Retrieve information from a changing HTML table

I am working on a nodejs express project that features a Dynamic Table within my application. Users can add or remove rows and enter values into cells, but I am struggling to extract these values from the table without using jquery. My goal is to then inse ...

Creating a dynamic `v-model` for computed properties that is dependent on the route parameter

I am creating a versatile component that can update different vuex properties based on the route parameter passed. Below is a simplified version of the code: <template> <div> <input v-model="this[$route.params.name]"/> </div&g ...

Is there a way to eliminate this pesky margin?

please check out this: https://jsfiddle.net/desytec/73qdtejg/1/#&togetherjs=w3lvLQi0v6 This displays the following table definition: <table id="semana" class="table table-striped dt-responsive table-bordered display ...