Bootstrap modal dialog, show.bs.modal event relatedTarget is undefined. How can I get clicked element?

eyn picture eyn · May 27, 2014 · Viewed 50.1k times · Source

Button invoked modal dialog: When button is clicked, event is fired the resulting event reference e.relatedTarget is undefined. So, how can I get the invoking button from the handler? e does not seem to contain any reference to the invoking button.

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

jQuery:

$('#myModal').on('show.bs.modal', function (e) {
  console.log(e.relatedTarget) // do something...
})

Reference: http://getbootstrap.com/javascript/#modals

Answer

JDev518 picture JDev518 · Aug 17, 2015

Thanks Geo1004.. I was already using JS to trigger the "show" event on the modal, but I was missing the second argument. So the event.relatedTarget was undefined.

If anyone else is going the JS route (instead of using data attributes) I would make sure you are sending the button as a jQuery object -

$( "#myModal" ).modal( "show", $( "#buttonBeingClicked" ) );