Bootstrap: Detect click on modal background

Created on 4 Aug 2018  路  4Comments  路  Source: twbs/bootstrap

Is there a way we can reliably detect a click on the modal background of the modal component (https://getbootstrap.com/docs/4.1/components/modal/#live-demo) using jQuery? There's not really anything under the usage section for this https://getbootstrap.com/docs/4.1/components/modal/#usage

Most helpful comment

@sts-ryan-holton, here you go: https://codepen.io/MartijnCuppens/pen/MBBjxX

document.querySelector('.modal').addEventListener('click', function(e) {
  // Check if the modal is clicked, not an element inside the modal:
  if (e.target === e.currentTarget) {
    console.log('Background is clicked');
  }
});

All 4 comments

You can listen to the click event of your modal, this event will be triggered when the modal background is clicked

@Johann-S Which class do I listen for? Could you provide me an example please?

@sts-ryan-holton, here you go: https://codepen.io/MartijnCuppens/pen/MBBjxX

document.querySelector('.modal').addEventListener('click', function(e) {
  // Check if the modal is clicked, not an element inside the modal:
  if (e.target === e.currentTarget) {
    console.log('Background is clicked');
  }
});

Thanks @MartijnCuppens 馃槈

Was this page helpful?
0 / 5 - 0 ratings