0

I have a modal that displays on a click event on my page. I've added an event listener to the 'close' link element in the top right of the modal, code as follows:

document.querySelector('.modal__close').addEventListener('click', () => {
            modal.style.display = 'none'
        })

This does indeed close/remove the modal, however, it also causes the page to 'jump' back up to the top (I've noticed it also adds a '#' to the end of the url), which is not the behaviour I want, how would I get the modal to just gracefully disappear and leave the underlying display exactly the same?

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
bevc
  • 203
  • 3
  • 14

2 Answers2

3

Probably that element is a link, so you should prevent its default action (which is to follow the link defined in the href attribute)

document.querySelector('.modal__close').addEventListener('click', (ev) => {
      modal.style.display = 'none';
      ev.preventDefault();
})

As a side note, you might use instead a <button> element, that could be more appropriate for this use case.

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

I think you have something like this :

<a href="" class="modal__close"></a>

By default, if the link (a) doesn't have a href defined, it reload the current page (and add a #).

To skip it, you can do it by preventing the default action in your Javascript with an event parameter :

document.querySelector('.modal__close').addEventListener('click', (ev) => {
     ev.preventDefault();
     modal.style.display = 'none';
});

and in jQuery it would be easier :

$('.modal__close').click(function(ev){
    ev.preventDefault();
    $(modal).css('display', 'none'); // can also be $(modal).hide();
});
Thomas Lamothe
  • 174
  • 1
  • 9