简体   繁体   中英

Modal opens and closes immediately

I am attempting to display a modal with results of a php query, after a button is submitted, but the modal flashes onto the screen, instead of remaining until it is manually closed, due to the fact that submitting a form refreshes the page.

<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("submitForm");
var span = document.getElementsByClassName("close")[0];
var form = document.getElementsByClassName("myForm")[0];

btn.addEventListener('click', openModal);
function openModal() {
    form.submit();
    modal.style.display = "block";
    console.log("shiet");
}

span.addEventListener('click', closeModal);
function closeModal(){
    modal.style.display = "none";
}

window.addEventListener('click', function(event){
  if (event.target == modal) {
    modal.style.display = "none";
  }
});
</script>

On clicking the button id=submitForm, I want a modal to pop up, containing the results of a php script. This modal can then be closed by clicking off the screen or by activating closeModal, by clicking a span element.

Try this:

window.addEventListener('click', function(event){
  if (event.target != modal) {
    modal.style.display = "none";
  } else {
    modal.style.display = "block";
  }
});

Here I meant that if the user is clicking on the window but not on the modal, then hide that; else keep the modal visible...

I think the modal flashes because of this reason!

I hope this works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM