-1

I'm trying to change the textcontent of a button in HTML using JavaScript.

It does reach the right if statement (the div is by default not showing), and if I use it on a random header in my HTML code it does change that.

// once page is loaded
window.addEventListener('DOMContentLoaded', (e) => {
  console.log('loaded');
  // get element, and run a function when clicked
  document.getElementById("toggleVisibilityButton").addEventListener("click", () => {
    console.log("show or hide method");

    let element = document.getElementById('reasonsNotConnectedDiv');
    let button = document.getElementById('toggleVisibilityButton');

    //If element is already hidden.
    if (element.style.display === "none") {
      //Change button style whether shown or not.
      button.textContent = 'Hide info ↑'

      //Make contents visible.
      element.style.display = "block"
    }

    //If element is not hidden.
    if (element.style.display === "block") {
      //Change button style whether shown or not.
      button.innerText = button.textContent = "See more ↓"

      //Make content invisible.
      element.style.display = "none"
    }
  });
});
<button name="toggleVisibilityButton" id="toggleVisibilityButton">See more ↓</button> and

I have tried different HTML variants of making a button as shown below as well.

// once page is loaded
window.addEventListener('DOMContentLoaded', (e) => {
  console.log('loaded');
  // get element, and run a function when clicked
  document.getElementById("toggleVisibilityButton").addEventListener("click", () => {
    console.log("show or hide method");

    let element = document.getElementById('reasonsNotConnectedDiv');
    let button = document.getElementById('toggleVisibilityButton');

    //If element is already hidden.
    if (element.style.display === "none") {
      //Change button style whether shown or not.
      button.textContent = 'Hide info ↑'

      //Make contents visible.
      element.style.display = "block"
    }

    //If element is not hidden.
    if (element.style.display === "block") {
      //Change button style whether shown or not.
      button.innerText = button.textContent = "See more ↓"

      //Make content invisible.
      element.style.display = "none"
    }
  });
});
<button name="toggleVisibilityButton" id="toggleVisibilityButton" value="See more ↓"></button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236

1 Answers1

1

The problem is that you are using two if statements one after another. Instead, convert the second if statement into an else statement or else if.

Whenever display is none and button is clicked, it first executes the code inside the first if statement, then since in this first if section display is turned into "block", the code also enters the second if section. Thus, it resets everything.

  • You should copy the relevant snippet from the question post (which has been updated) and modify it to demonstrate your answer. – isherwood Jun 18 '21 at 16:18