Ken Mayer Ken Mayer - 1 month ago 15
HTML Question

Bootstrap Popover AND a Modal (hover and click)

Scenario: user profile. I would like to be able to display a user name with a popover that displays a limited amount of information from the user profile. So far, I have that part working. I can build it on the fly and have it do what I need. The popover works perfectly.

What I would also like to do is have the user be able to click on the user name and bring up a Bootstrap modal form with more information about the user (if provided). The first problem I am seeing is that it appears the data-toggle attribute can only have a single setting:

echo '<a href="#" class="trigger userprof" data-toggle="popover" data-target="#userModal" data-popover-content="#content' . $user_row['user_id'] . '">' . $user_row['user_name'] . '</a>';


In that example, if I add the modal to the data-toggle attribute it doesn't seem to do me much good.

I have discovered by tinkering (and that is why the class 'userprof' in the code above), that a JavaScript click event can be triggered (right now all I'm doing is a basic JS alert dialog to test), but from there I would want to load the modal. I am not sure if I can make it all work.

I have a set of functions I've used successfully for another modal (calling this one 'userModal') that I got some help from someone here a while back with -- is it possible to call that from the click event?

// code to open the modal with the caption and description:
$('#userModal').on('show.bs.modal', function (event)
{
var button = $(event.relatedTarget); // Button that triggered the modal
var title = button.data('title'); // Extract info from data-* attributes
var body = button.data('body'); // Extract info from data-* attributes
var modal = $(this);
modal.find('.modal-title').text( title );
modal.find('.modal-body').append( body );
});

// when modal closes, clear out the body:
$('#userModal').on('hidden.bs.modal', function ()
{
$(this).find(".modal-body").text('');
});


Since these are "anonymous" functions I am not sure I can call them ... feeling a bit lost in the code here. Any help pointing me in the right direction would be great. I'd even be willing to consider a different idea, but I would like this kind of functionality (hover and click) for this situation and possibly something else. Thanks!

Answer

You're listening for the modal to show itself, when the DOM is showing the modal.

try using something like this, and use a button or a link with data-toggle="modal"

$(document).on('hidden.bs.modal', '#userModal', function ()
{
    $(this).find(".modal-body").text('');
});

for reference https://jsfiddle.net/y063mu4t/1/