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

Apply javascript click function to toggle an HTML element

I am new to Javascript and trying to create a Javascript click function that will display the input element when the button is clicked and hide it when the button is clicked again. My console shows no error messages but when I click the button the input element does not hide. Again I am very new to Javascript, I appreciate any feedback!

document.addEventListener("DOMContentLoaded", load);

function load() {
  let button = document.querySelector("button");

  button.addEventListener("click", clickMe);
}

// Click Function to change the display value of the input
function clickMe() {
  let input = document.getElementById("popup");

  if (input.style.display == "none") {
    input.style.display = "block";
  } else {
    input.style.display = "none";
  }
}
<!-- <form> I commented out the form element because it does not work to use .addEventListener inside form -->
<label for="button"></label>
<fieldset>
  <ol>
    <li><button type="button" onclick="clickMe()">Click me!</button></li>
    <li><input type="text" name="popup" id="popup" placeholder="placeholder"></li>
  </ol>
</fieldset>
<!-- </form> -->

>Solution :

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

Two things:

  1. You don’t need to add both the onclick attribute and an event listener. Just use .addEventListener, it is the preferred way.
  2. Don’t use tag selectors unless you really want to affect every <button> element. In your case, you should use an ID, such as "clickMeBtn".
document.addEventListener("DOMContentLoaded", load);

function load() {
  let button = document.querySelector("#clickMeBtn");
  button.addEventListener("click", clickMe);
}

// Click Function to change the display value of the input
function clickMe() {
  let popup = document.getElementById("popup");
  if (popup.style.display == "none") {
    popup.style.display = "block";
  } else {
    popup.style.display = "none";
  }
}
<form>
  <label for="button"></label>
  <fieldset>
    <ol>
      <li><button type="button" id="clickMeBtn">Click me!</button></li>
      <li><input type="text" id="popup" name="popup" placeholder="placeholder"></li>
    </ol>
  </fieldset>
</form>
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