I'm placing the following content in a Twitter Bootstrap popover, which contains a link for which I want to listen for clicks:
<div id="popover-content">
<a id="link" href="#">click</a>
</div>
I'm using a button to reveal the popover which contains the above content:
<button id="trigger" data-placement="bottom" title="title">Reveal popover</button>
I then associate the button with the popover and use jQuery's click()
function in attempt to listen for clicks on the link contained in the popover:
$(function(){
$('#trigger').popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
$('#link').click(function() {
alert('beep');
});
});
However, upon clicking the button to reveal the popover and then clicking the link, the click seems to not be detected as intended above. My understanding of the DOM and javascript and jQuery is fairly limited, so I'm not sure what's going on here. How can you select/listen for actions on elements contained in a popover?
Reference: Popovers in Bootstrap
To show or hide the Popover programmatically, call the show() or hide() method. The same thing can be done using the toggle(showing) method. Pass true or false to this method to show or hide the Popover, respectively. This approach is more typical of jQuery Controls.
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.
To create a popover, you need to add the data-bs-toggle="popover" attribute to an element. Whereas, popover's title and its content that would display upon trigger or activation can be specified using the title and data-bs-content attribute respectively. Here is the standard markup for adding a popover to a button.
Tooltip: use tooltips to show a short text to respondents when they hover over a word or icon. Popover: use popovers to show a longer text, or when you want to have a link to an external web page. It is shown when the respondent clicks on a word or icon.
You do not need to perform Event delegation here.Instead use $('#popover-content')
instead of $('#popover-content').html()
while setting the content. This will have the events registered attached by default without requiring any delegation.
$(function(){
$('#trigger').popover({
html: true,
content: function() {
return $('#popover-content'); //<-- Remove .html()
}
});
$('#link').click(function() {
alert('beep');
});
});
You can try this:
$(document).on('click', '#link', function(){
alert('beep');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With