M
M
Murad Jelilov2014-08-27 10:56:56
JavaScript
Murad Jelilov, 2014-08-27 10:56:56

How to intercept click outside bootstrap modal?

Good afternoon. How can you intercept a click outside of a bootstrap modal?
Tried to do like this:

$('#modalfoto').on('hidden.bs.modal', function (e) {
    alert('Модальное окно!');
});

so:
$( ".modal-backdrop" ).click(function() {
  alert( "Модальное окно!" );
});

Didn't earn shit

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Petrov, 2014-08-27
@Petroveg

The method "on the forehead" - we look at the ancestors in search of a window

$(document).on('click', function () {
  if (!$(this).closest('#modalfoto').length) {
    console.log('Это — не моя клетка!');
  }
});

The way is more elegant - we use the sequence of nodes during the ascent. Since the event will pass through the element called the “modal window” in any way earlier than through the document, we hook the trailer and only check for its presence in the document.
$(document)
  .on('click', '#modalfoto', function (e) {
    e.modalWindow = true;
  })
  .on('click', function (e) {
    if (!e.modalWindow) {
      console.log('Это — не моя клетка!');
    }
  });

A
Alexey Nikolaev, 2014-08-27
@Heian

It didn't work on modal-backdrop because #modalfoto dominates it. Therefore, I would add a click event on #modalfoto, which would include a check for the click coordinates. If the user clicked outside the div, we handle the event, if not, we do nothing.
He sketched out an approximate scheme of actions.

$("#modalfoto").click(function(e){
  var modalDialog = $(this).find('.modal-dialog');
  var xOffset = modalDialog.offset().left;
  var yOffset = modalDialog.offset().top;
  if((e.pageX < xOffset || e.pageX > xOffset + modalDialog.width()) &&
     (e.pageY < yOffset || e.pageY > yOffset + modalDialog.height()) {
     // какие-то действия
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question