Click It...">

Get the item that closed the modal

In my HTML, I have this in one of my modals:

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

It hides modality if this element is clicked.

However, I want to get the element that closed the modal in jQuery, for example:

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

But that does not work. relatedTarget only works for show.bs.modal and shown.bs.modal ( as per the documentation ).

How can I get the element that caused the modality closure in the hidden.bs.modal event?

+6
source share
1 answer

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

So, to get the element that was clicked to close the modal, I used the jQuery selector functions. Like this:

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

In this case, jQuery searches for each element with the data-dismiss with the value modal and attaches a callback function to the elements found that is executed when clicked.

As you can see in the example I did, there are two buttons with this attribute. One in the modal header:

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

And one more in the modal footer:

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

Both of these buttons have different identifiers that I set to show that you can check which one was pressed through $(this).attr('id') in the callback function associated with the click event.

+1
source

Source: https://habr.com/ru/post/1012867/


All Articles