Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach event handler to button in twitter bootstrap popover

I am using the twitter bootstrap popovers,

In the popover I am adding a button,

I need to attach a click handler to the button, but the way popover works is each time it shows it removes and re-creates the element, instead of just showing/hiding it, hence removing any event handlers I have associated with said button.

I am creating several popovers all with their own version of the button, so just applying a class to the popover won't work (unless I generate a different class for each one :/), the button may or may not have it's own ID, so cannot apply an ID.

How can I apply a event handler to something in the contents of the twitter bootstrap popover?

like image 213
Hailwood Avatar asked Nov 03 '12 01:11

Hailwood


People also ask

How do I use Bootstrap Popovers?

How To Create a Popover. To create a popover, add the data-toggle="popover" attribute to an element. Note: Popovers must be initialized with jQuery: select the specified element and call the popover() method.

How do I show popover on hover?

Set the trigger option of the popover to hover instead of click , which is the default one. Or with an initialization option: $("#popover"). popover({ trigger: "hover" });

How do I use popover in bootstrap 5?

To create a popover, add the data-bs-toggle="popover" attribute to an element. Note: Popovers must be initialized with JavaScript to work.


1 Answers

I had the same problem, and, in my case, the $(body).on('click') workaround won't work, since the application has lotta click buttons.

I did the following instead. This way, we can limit the scope of the delegate event to just the parent of the popover element.

$('a.foo').popover({     html: true,     title: 'Hello',     placement: 'bottom',     content: '<button id="close-me">Close Me!</button>' }).parent().delegate('button#close-me', 'click', function() {     console.log('World!'); }); 

JS Fiddle: http://jsfiddle.net/dashk/5Yz7z/

P.S. I used this technique in within a Backbone.View in my application. Here's the snippet of the code in Fiddle, in case you're using this in Backbone.js as well...: http://jsfiddle.net/dashk/PA6wY/

EDITED In Bootstrap 2.3, you can specify a target container which popover will be added to. Now, instead of doing the .parent() locator, you can also listen to events specifically to the container... This can make the listener even more specific (Imagine creating a DIV that only exists to contain the popover.)

like image 136
DashK Avatar answered Sep 24 '22 00:09

DashK