Home > Net >  Modal disappearing instantly
Modal disappearing instantly

Time:03-26

I am a beginner, trying to implement 'click' event listener to pop up a modal. But as soon as I click the link the modal appears and disappear instantly.

const btn = document.getElementById(btn");
const modal= document.getElementById("modal");

const showModal = function (el, modalId) {
  el.addEventListener("click", function () {
    modalId.classList.remove("hidden");
  });
};

showModal(btn, modal);
.hidden{
 display: none
}
<a class='btn'> Click </a>
<div id='modal' class='hidden'> Modal Content </div>

CodePudding user response:

you should define id="btn" on your a tag to be able to do document.getElementById("btn")

const btn = document.getElementById("btn");
    const modal = document.getElementById("modal");

    const showModal = function(el, modalId) {
      el.addEventListener("click", function() {
        modalId.classList.remove("hidden");
      });
    };

    showModal(btn, modal);
.hidden {
  display: none
}
<a id="btn"> Click </a>
<div id='modal' class='hidden'> Modal Content </div>

CodePudding user response:

Thanks You so much guys for responding. I found my mistake, I was using 'link' tag with empty 'href' attribute, due to which the page was reloading ever time I clicked it. I simply replaced the links with button tag and now it is working just fine.

Although I still want to know if it is possible to stop the page from reloading when link element is clicked.

Also, thank you for highlighting the 'class/id' typo.

  • Related