skip to Main Content

I am creating a small JavaScript function to open or close a div-element, without jQuery but just a small JavaScript and CSS and it is working but I want to achieve the following:

The div starts always hidden when loading the page (done)

If the visitor clicks on "OPEN"-button, the div is displayed and the text "OPEN" must be changed in this save button to "CLOSE" and so on, depending if the div is open or closed we display the text: OPEN or CLOSE (working on it and need help with it)

Here is an updated Codepen with it:
https://codepen.io/familias/pen/WNYQeqQ

var LetsDoThis = document.querySelector("#toggle");
var LetsDoThat = document.querySelector("#content");

LetsDoThis.addEventListener("click", function() {
  LetsDoThat.classList.toggle("hidden");
});
.hidden {
  display: none;
}
<button id="toggle">OPEN</button>
<div id="content" class="hidden">
  When the "OPEN" button is clicked, the text must change from OPEN to CLOSE, all depending if it is open or closed
</div>

How can I accomplish that ?

3

Answers


  1. You can do this by checking the text of the button:

    var LetsDoThis = document.querySelector("#toggle");
    var LetsDoThat = document.querySelector("#content");
    
    LetsDoThis.addEventListener("click", function() {
      LetsDoThat.classList.toggle("hidden");
      (LetsDoThis.innerHTML == 'OPEN') ? LetsDoThis.innerHTML = 'CLOSED': LetsDoThis.innerHTML = 'OPEN';
    
    });
    .hidden {
      display: none;
    }
    <button id="toggle">OPEN</button>
    <div id="content" class="hidden">
      When the "OPEN" button is clicked, the text must change from OPEN to CLOSE, all depending if it is open or closed
    </div>
    Login or Signup to reply.
  2. Modifying the event handler to include the button as follows.

    LetsDoThis.addEventListener("click", function() {
      LetsDoThat.classList.toggle("hidden");
      LetsDoThis.innerText = LetsDoThis.innerText === "OPEN" ? "CLOSE" : "OPEN";
    });
    
    Login or Signup to reply.
  3. See if that fixes it:

    var LetsDoThis = document.querySelector("#toggle");
    var LetsDoThat = document.querySelector("#content");
    
    LetsDoThis.addEventListener("click", function({ currentTarget }) {
      // true if the class is added or false if it is removed
      let isOpen = LetsDoThat.classList.toggle("hidden");
      
      currentTarget.textContent = isOpen ? 'OPEN' : 'CLOSE'
    });
    .hidden {
      display: none;
    }
    <button id="toggle">OPEN</button>
    <div id="content" class="hidden">
      When the "OPEN" button is clicked, the text must change from OPEN to CLOSE, all depending if it is open or closed
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search