Bootstrap Popover, .click not catching button inside popover

Tim Habersack picture Tim Habersack · Jul 16, 2013 · Viewed 28.1k times · Source

First off, a fiddle of the problem: jsfiddle.net

I am using a popover, and it's content is html, a button with class "click_me". I have jquery to listen for a click on "click_me" and it should throw an alert. However, it doesn't. Am I missing something?

JS:

jQuery(document).ready(function($) {

$('.demo_button').click(function () {
    $(this).popover({
                html: true,
                trigger: 'manual',
                placement: 'right',
                content: function () {
                    var $buttons = $('#popover_template').html();
                    return $buttons;
                }
    }).popover('toggle');
});

$('.click_me').click(function() {
    alert('it works!');
});

});

HTML:

<button class="btn btn-primary demo_button">Click here</button>

<div id="popover_template">
    <button class="btn click_me">Make Alert</button>
</div>

Answer

Stefan picture Stefan · Jul 16, 2013

.click() will only work for elements that are present on load you need to use on()

$(document).on("click", ".click_me", function() {
    alert('it works!');
});