How to get Twitter Bootstrap Modal's invoker element? How to get Twitter Bootstrap Modal's invoker element? javascript javascript

How to get Twitter Bootstrap Modal's invoker element?


It was solved in Bootstrap 3.0.0 thanks to event.relatedTarget.

$('#your-modal').on('show.bs.modal', function (e) {  var $invoker = $(e.relatedTarget);});


You have to listen to:

$('[data-toggle="modal"]').on('click', function() {    $($(this).attr('href')).data('trigger', this);});$('.modal').on('show.bs.modal', function() {    console.log('Modal is triggered by ' + $(this).data('trigger'));});

You can of course replace show.bs.modal with shown.bs.modal or any other event they fire.Note that this is for Bootstrap 3.0.0. If you're using 2.3.2 you need to get rid of .bs.modal (I think).

What I like about this solution: you do not have to remember who is this, self, that and other proxy calls workarounds.

Of course, you have to test if the href attribute is not a real link (the dynamic modal loading option).


The modal element has a data object named modal that saves all the options that are passed. You can set a 'source' data attribute on the element that triggers the modal, set it to the ID of the source, and then retrieve it later from the options variable.

The trigger would be:

<a id="launch-modal-1" class="btn" data-toggle="modal" data-target="#myModal" href="http://some-url" data-source="#launch-modal-1">Launch Modal</a>

In the event callback, get the modal data object, and look at the source option:

$('#myModal').on('hidden', function () {  var modal = $(this).data('modal');  var $trigger = $(modal.options.source);  // $trigger is the #launch-modal-1 jQuery object});