How to get Twitter Bootstrap Modal's invoker element?

I have got a a element for invoking modal:

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

And, say this is my modal:

<div class="modal hide" id="myModal">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
  </div>
  <div class="modal-body">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <a href="#" class="btn" data-dismiss="modal">Close</a>
    <a href="#" class="btn btn-primary">Save changes</a>
  </div>
</div>

I can bind functions to events fired by modal:

$('#myModal').on('hidden', function () {
  // do something…
})

My question is: How can i access the a element -which invoked the modal- from my event subscriber function?


Solution 1:

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

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

Solution 2:

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).

Solution 3:

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
});

Solution 4:

Currently it's not available out-of-box. There is a feature request for it and a work-around if you want to edit the bootstrap-modal code yourself.

See here