Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger DIV content on button click + change button text

I am trying to trigger the visibility of a DIV via a button.

My code looks like this:

function myFunction() {
var moreText = document.getElementById("csrmore");
var x = document.getElementById("myDIV");
  let ishidden = x.classList.contains("hidden")
if (ishidden == true) {
x.classList.remove("hidden");
x.classList.add("shown");
moreText.innerHTML = "Show less";
}
else  {
x.classList.remove("shown");
x.classList.add("hidden");
moreText.innerHTML = "Show more";
}   
}
div {
  width: 100px;
  height: 100px;
}

.hidden {
  display:none
}

.shown {
  display:block;
}
<button id="csrmore" onclick="myFunction()">
Show more
</button>


<div id="myDIV" class="hidden">
This is the triggerable content.
</div>

Fiddle: https://jsfiddle.net/6zxa0Lg2/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It works fine, however since I am a JS starter, I was wondering if this is bad practice or is it a totally fine piece of code?

Thanks for every help 🙂

>Solution :

Here’s another way to go about it. Make it all relative. The button is clicked and the javascript finds the content associated to that button to show/hide. This way you don’t need any ID tags and you can have as many show/hide buttons as you want on the page.

document.addEventListener('DOMContentLoaded', () => {
  // after the page loads...
  document.querySelectorAll('.csrmore').forEach(button => {
    // find all the 'show more' buttons and for each one...
    button.addEventListener('click', e => {
      // when someone clicks this button
      let content = e.target.closest('.container').querySelector('.content');
      // find the content div associated with this button
      content.classList.toggle('hidden');
      // toggle on or off the content
      e.target.innerText = content.classList.contains('hidden') ? 'Show more' : 'Hide';
      // change the text of the button
    })

  })
})
div {
  width: 100px;
  height: 100px;
}

.hidden {
  display: none
}
<div class='container'>
  <button class="csrmore">
Show more
</button>
  <div class="content hidden">
    This is the triggerable content.
  </div>
</div>

<hr>

<div class='container'>
  <button class="csrmore">
Show more
</button>
  <div class="content hidden">
    This is the triggerable content.
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading