Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the element that closed the modal

In my HTML I have this within one of my modals:

<a href="#" class="clicker" data-dismiss="modal">Click</a>

It hides the modal if this element is clicked.

However, I want to be able to get the element that closed the modal in jQuery, like:

$('#myModal').on('hidden.bs.modal', function(event)
{
    var invoker = $(event.relatedTarget);
});

But this doesn't work. relatedTarget seems to only work for show.bs.modal and shown.bs.modal (as per the documentation).

How then can I get the element that caused the modal to close in the hidden.bs.modal event?

like image 394
user7246775 Avatar asked Dec 04 '16 01:12

user7246775


1 Answers

I have made a Pen to show how to achieve the desired result. As you can see in this example, the events spawned by Bootstrap do not share the exact element used to close a modal. They reference, as the .target and .currentTarget, the whole modal element itself.

So, in order to get the element that was clicked to close the modal, I have used jQuery selector functionality. Like this:

$("[data-dismiss='modal']").click(function() {
  $("#data-dismiss").html('#'+ $(this).attr('id'));
});

In this case, jQuery is searching for every element that has the attribute data-dismiss with the value modal and attaching, to those elements found, a callback function that is executed when they are clicked.

As you can see in the example that I have made, there are two buttons with this attribute. One in the modal's header:

<button id="header-close-button" type="button"
        class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">&times;</span>
</button>

And another one in the modal's footer:

<button id="footer-close-button" type="button"
        class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">Close</span>
</button>

Both these buttons have different ids that I set to show that you can check which one exactly was clicked - through the $(this).attr('id') on the callback function attached to the click event.

like image 59
Bruno Krebs Avatar answered Oct 02 '22 02:10

Bruno Krebs