Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you!

   function descriptionHeightMore(){
          var myElement = document.querySelector(".backwhite");
        myElement.style.height = "auto";
        }
 .backwhite{
        background-color: aqua;
        padding:15px;
        height:50px;
        overflow:hidden;
      }
   <div class="container">
     <div class="backwhite">
     <p>1. Create Ui For Email Campaign.</p>
     <p>2. Create Functionality of Email Campaign</p>
     <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
     <p>1. Create Ui For Email Campaign.</p>
     <p>2. Create Functionality of Email Campaign</p>
     <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
     <p>1. Create Ui For Email Campaign.</p>
     <p>2. Create Functionality of Email Campaign</p>
     <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
    </div>
    <button type="button" class="btn btn-default btn-block"     onclick="descriptionHeightMore();">Expand</button>
    </div>

Answer №1

Check out this neat JavaScript solution

To begin, let's define a custom class named .expanded that we can toggle on and off -

.highlight.expanded {
    height: auto;
}

Then, I updated the JavaScript code to toggle the .expanded class and change the button text accordingly -

function expandDescription(e) {

  // Toggle .expanded class
  document.querySelector(".highlight").classList.toggle('expanded');

  // Update button text
  e.target.textContent == 'Open' ? e.target.textContent = 'Close' : e.target.textContent = 'Open'; 

}

// Listen for button clicks   
var btn = document.querySelector('.toggle-btn');
btn.addEventListener('click', expandDescription)

Try it yourself in action on CodePen - http://codepen.io/ire/pen/wgyvYw

Answer №2

Give this JavaScript code a try to dynamically adjust element height based on conditions:

function descriptionHeightMore(){
    var myElement = document.querySelector(".backwhite");
        if(myElement.style.height == "auto"){
            myElement.style.height = "50px";
        }else{
            myElement.style.height = "auto";
        }
}
.backwhite{
    background-color: aqua;
    padding:15px;
    height:50px;
    overflow:hidden;
}
<div class="container">
<div class="backwhite">
<p>1. Create Ui For Email Campaign.</p>
<p>2. Create Functionality of Email Campaign</p>
<p>3. Create Keyword Display using Drag And Drop Functionality.</p>
<p>1. Create Ui For Email Campaign.</p>
<p>2. Create Functionality of Email Campaign</p>
<p>3. Create Keyword Display using Drag And Drop Functionality.</p>
<p>1. Create Ui For Email Campaign.</p>
<p>2. Create Functionality of Email Campaign</p>
<p>3. Create Keyword Display using Drag And Drop Functionality.</p>
</div>
<button type="button" class="btn btn-default btn-block"  onclick="descriptionHeightMore();">Toggle</button>
</div>

Answer №3

It may seem impossible to get the height of an element using JavaScript, but with a button that changes the height, you can easily toggle between different heights by checking the button text.

function adjustHeight(t){
          var myElement = document.querySelector(".backwhite");       
          if(t.innerHTML == "Expand") {
            myElement.style.height = "auto";
            t.innerHTML = "Collapse";
            }
          else {
            myElement.style.height = "50px";
            t.innerHTML = "Expand";
            }
        }
.backwhite{
        background-color: aqua;
        padding:15px;
        height:50px;
        overflow:hidden;
      }
<div class="container">
     <div class="backwhite">
     <p>1. Create Ui For Email Campaign.</p>
     <p>2. Create Functionality of Email Campaign</p>
     <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
     <p>1. Create Ui For Email Campaign.</p>
     <p>2. Create Functionality of Email Campaign</p>
     <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
     <p>1. Create Ui For Email Campaign.</p>
     <p>2. Create Functionality of Email Campaign</p>
     <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
    </div>
    <button type="button" class="btn btn-default btn-block" onclick="adjustHeight(this);">Expand</button>
    </div>

Answer №4

If you've already identified the question using jQuery, toggling a class can help you achieve this task effortlessly.

Here is an example:https://jsfiddle.net/abc123/

<script>
   function expandDescription(){
      var element = document.querySelector(".backwhite");
      $(element).toggleClass("expandedHeight");
   }
</script>

CSS

.expandedHeight {
   height: 100%;
}

Answer №5

$(".btn").click(function() {

  $(".backwhite").toggleClass("overflow")
  $(".backwhite").hasClass("overflow") ? $(".btn").text("Expand") : $(".btn").text("Compress")

})
.backwhite {
  background-color: aqua;
  padding: 15px;
  height: 50px;
}
.overflow {
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="backwhite overflow">
    <p>1. Create Ui For Email Campaign.</p>
    <p>2. Create Functionality of Email Campaign</p>
    <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
    <p>1. Create Ui For Email Campaign.</p>
    <p>2. Create Functionality of Email Campaign</p>
    <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
    <p>1. Create Ui For Email Campaign.</p>
    <p>2. Create Functionality of Email Campaign</p>
    <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
  </div>
  <button type="button" class="btn btn-default btn-block">Expand</button>
</div>

  1. implement the use of .toggleClass()
  2. ensure there is a specific class for overflow.
  3. toggle the content accordingly

Answer №6

Hey everyone, take a look at this!

<!DOCTYPE html>
<html>
<head>
<style type="text/css>

   .backwhite{
    background-color: aqua;
    padding:15px;
    height:50px;
    overflow:hidden;
  } 

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
     var myElement = document.querySelector(".backwhite");

     if(myElement.style.height == "auto"){
     myElement.style.height = "50px";
    }else{
        myElement.style.height = "auto";
    }
    });
});

</script>
</head>
<body>

 <div class="backwhite">
 <p>1. Design User Interface For Email Campaign.</p>
 <p>2. Implement Functionality of Email Campaign</p>
 <p>3. Develop Keyword Display using Drag And Drop Feature.</p>
 <p>1. Design User Interface For Email Campaign.</p>
 <p>2. Implement Functionality of Email Campaign</p>
 <p>3. Develop Keyword Display using Drag And Drop Feature.</p>
 <p>1. Design User Interface For Email Campaign.</p>
 <p>2. Implement Functionality of Email Campaign</p>
 <p>3. Develop Keyword Display using Drag And Drop Feature.</p>
</div>

<button type="button">Toggle</button>

</body>
</html>

Answer №7

Give this code a shot! When you click the button, it will toggle the overflow property and change the button text. Best of luck!

<html>

  <head>
  </head>

  <body>
    <script>
      function adjustHeight() {
        var element = document.querySelector(".backwhite");
        element.style.height = "auto";
        if (element.style.overflow == "hidden")
          element.style.overflow = "visible";
        else
          element.style.overflow = "hidden";
        var button = document.getElementsByTagName("button")[0];
        if (button.innerHTML === "Expand")
          button.innerHTML = "Collapse";
        else
          button.innerHTML = "Expand";
      }
    </script>

    <style>
      .backwhite {
        background-color: aqua;
        padding: 15px;
        height: 50px;
        overflow: hidden;
      }
    </style>

    <div class="container">
    <div class="backwhite">
      <p>1. Create Ui For Email Campaign.</p>
      <p>2. Create Functionality of Email Campaign</p>
      <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
      <p>1. Create Ui For Email Campaign.</p>
      <p>2. Create Functionality of Email Campaign</p>
      <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
    </div>
    <button type="button" class="btn btn-default btn-block" onclick="adjustHeight();">Expand</button>
  </div>
</body>

</html>

function adjustHeight() {
  var element = document.querySelector(".backwhite");
  element.style.height = "auto";
  if (element.style.overflow == "hidden")
    element.style.overflow = "visible";
  else
    element.style.overflow = "hidden";
  var myButton = document.getElementsByTagName("button");
  if (myButton.value == "expand")
    myButton.value = "collapse";
  else
    myButton.value = "expand";
}
.backwhite {
  background-color: aqua;
  padding: 15px;
  height: 50px;
  overflow: hidden;
}
<div class="container">
  <div class="backwhite">
    <p>1. Create Ui For Email Campaign.</p>
    <p>2. Create Functionality of Email Campaign</p>
    <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
    <p>1. Create Ui For Email Campaign.</p>
    <p>2. Create Functionality of Email Campaign</p>
    <p>3. Create Keyword Display using Drag And Drop Functionality.</p>
  </div>
  <button type="button" class="btn btn-default btn-block" onclick="adjustHeight();">Expand</button>
</div>

Answer №8

Make use of the jQuery toggle method Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>

<p>Here is a sample text.</p>

<button>Toggle between hide() and show()</button>

</body>
</html>

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

Ways to remove a JSON item based on its index position?

In my JSON object, I am trying to find a way to remove the first element. Here is an example of what I have: var obj1 = {property:'something', does:'somethingElse', is:'somethingCool'}; var obj2 = {does:'somethingElse&ap ...

Guide on Creating HTML Embeds for Multiple Selection Code Blocks

I need some help creating a feature similar to this: View Image Unfortunately, I haven't been able to locate any tutorials or code samples on how to implement multi-selectable language code blocks using HTML/CSS. My CSS knowledge is limited, and I r ...

Efficiently loading components in Angular using browserify with lazy loading

As I work on developing the architecture of a complex application with Angular, I have started with the angular-seed project which seems to be a solid starting point. However, one issue that concerns me is how Angular apps tend to load everything upfront b ...

Is the object in handlebars referring to the context?

After encoding the database response in json, I ended up with a unique structure that was sent through echo from a controller using json_encode (I usually work in php): [ {column1: value, column2: value...} //row 1 {column1: value, column2: val ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

show data pulled from localStorage

I'm struggling to figure out how to use localStorage for the first time, specifically in storing an array of objects and displaying that information even after page refresh. Currently, I can see that it is being stored but not displayed. const book ...

Are there distinctions between using app.use("/", express.static) versus app.use(express.static)?

Is there a distinction between the following scenarios, assuming we have already executed app.set('thePath', thePath)? app.use('/', express.static(thePath)) app.use(express.static(thePath)) app.use(express.static(app.get('thePath ...

Getting the input tag id of an HTML form can be achieved by using the "id

<?php $i = 1; $query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page.""); while($result = mysql_fetch_array($query1)){ echo '<td colspan = "2">& ...

AngularJS Expandable Table - Unlocking Limitless Possibilities

Take a look at the code snippet below: <tbody> <tr ng-repeat-start="ticket in tickets"> <td> <button ng-if="ticket.expanded" ng-click="ticket.expanded = false">-</button> <button ng-if="!t ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

Remove inline CSS from HTML elements

Having a large HTML file structured like this: <div style="min-height: 32px; padding: 5px; width: 800px; margin: 50px auto; overflow: auto; font-size: 12px;" class="selectable clearfix selected_layer" id="wrap"> <div class="selectable" id="l1" st ...

The screen reader seems to be malfunctioning as soon as I include this particular code

//Finding the height of the header let headerHeight = document.querySelector('header'); let height = headerHeight.offsetHeight; //Adjusting the #navbarNav's top margin to accommodate the header let nn = docu ...

The console correctly detects the value, but is unable to set the innerHTML property of null

I am currently working on a webpage that allows users to sign in and create an account. The issue I'm facing is that when I try to display the user's information, I encounter the error 'Cannot set property 'innerHTML' of null.&apos ...

Unable to establish a connection with the endpoint

I'm encountering an issue while trying to connect to the endpoint on the server. Below is the code snippet: Register.jsx function Register() { const [registerUser, setRegisterUser] = useState({ username: "", email: "", password: "", ...

executing several asynchronous requests upon loading the webpage in a single-page application

As a newcomer to front end development, I have a question about page rendering performance. In my single page application, I have utilized multiple Ajax calls to retrieve data for manipulation in order to enhance performance. However, I am concerned that ...

Issue with html2canvas image download in Firefox

I am currently using HTML2Canvas to try and download a div as an image. It works perfectly fine on Google Chrome, but I am experiencing issues with Firefox. Below is the code snippet: <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0. ...

Adding a collection of icons to an accordion using Jquery

Currently seeking a jquery accordion plugin that offers the ability for each panel to feature a draggable icon gallery. ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

The best practices for utilizing getStaticProps with Firebase

I am completely new to Next.js and am struggling to make the getStaticProps function work properly. import firebase from '../firebase' export default function Home({ posts }) { return ( <div> <h1>All Posts</h1> ...

Moving a popup div along with a marker in Leaflet can be achieved by using the set

After creating a map using leaflet and adding markers to different locations, I implemented code that displays a popup div with a message when a marker is clicked. Here is the code snippet: markers.on("click", function(d) { div.html("This is Some info ...