Related
Edit: I guess part of this is an issue of me being inexperienced with Drupal. I added a javascript file to site.info, so that it will be added to every page. This is all the file contains:
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
When the site loads, it gets compiled into this larger script, which looks like this in the debugger:
(function ($) {
Drupal.behaviors.titlebar = {
init: function(context, settings) {
// Using percentage font size to easily increase/decrease page font size
var baseFontSize = 100;
$('.pgc-font-size a').click(function() {
if($(this).hasClass('increase')) {
if(baseFontSize < 150)
baseFontSize += 20;
$('.pg-content-body p').css('font-size', baseFontSize+'%');
} else {
if(baseFontSize > 70)
baseFontSize -= 10;
$('.pg-content-body p').css('font-size', baseFontSize+'%');
}
});
// Print button
$('.pgc-print a').click(function() {
window.print();
})
}
};
}(jQuery));
// There's a problem with our jQuery loading before the ingested site's
// jQuery which is causing jQuery plugins to break (the "once" plugin in this case).
// I'm using this workaround for now
jQuery(function() {
Drupal.behaviors.titlebar.init();
});;
(function ($) {
Drupal.behaviors.giftTypes = {
init: function() {
// Gift details accordion
$('.pg-gift-details .accordion-items').css('display', 'none');
$('.pg-gift-details .accordion-switch').click(function(){
if($(this).hasClass('open')) {
$(this).find('span').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$('.pg-gift-details .accordion-items').slideUp('slow');
$(this).html($(this).html().replace('Hide', 'Show More'));
$(this).removeClass('open');
} else {
$(this).find('span').removeClass('icon-arrow-down').addClass('icon-arrow-up');
$('.pg-gift-details .accordion-items').slideDown('slow');
$(this).html($(this).html().replace('Show More', 'Hide'));
$(this).addClass('open');
}
})
}
}
}(jQuery));
// There's a problem with our jQuery loading before the ingested site's
// jQuery which is causing jQuery plugins to break (the "once" plugin in this case).
// I'm using this workaround for now
jQuery(function() {
Drupal.behaviors.giftTypes.init();
});;
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
alert(searchVal);
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
;
You can see my little script at the bottom there. It says there's something wrong with the first line, but I'm not sure what the problem is. What change would I need to make to my javascript file to make sure it compiles right?
I'm probably overlooking a really simple type, but I can't see what's wrong with my jQuery.
This is the part that's not working:
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.website.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
I have jQuery on my site, I know I do because this it's used earlier in the code with no problem. The error is showing in the debugger on the first line, '$("#ct100_btnSearch001").on("click", function(){ '. Here is a larger section of the script page:
(function($) {
Drupal.behaviors.giftTypes = {
init: function() {
// Gift details accordion
$('.pg-gift-details .accordion-items').css('display', 'none');
$('.pg-gift-details .accordion-switch').click(function() {
if ($(this).hasClass('open')) {
$(this).find('span').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$('.pg-gift-details .accordion-items').slideUp('slow');
$(this).html($(this).html().replace('Hide', 'Show More'));
$(this).removeClass('open');
} else {
$(this).find('span').removeClass('icon-arrow-down').addClass('icon-arrow-up');
$('.pg-gift-details .accordion-items').slideDown('slow');
$(this).html($(this).html().replace('Show More', 'Hide'));
$(this).addClass('open');
}
})
}
}
}(jQuery));
jQuery(function() {
Drupal.behaviors.giftTypes.init();
});;
(function($) {
$("#ctl00_btnSearch001").on("click", function() {
var searchVal = $("#ctl00_txtSearch").val();
alert(searchVal);
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);;
Try to install jQuery update Module.
If you are using Drupal 6, you are not be able to use on function.
One option is to include your custom version of jQuery in your page.tpl.php, another option (not recommended) is to use live, but now is deprecated.
You can bind a function to an event use two way:
1.use bind() method and the event name as the first argument
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
or
2.just use the event method
$( "#foo" ).click( function() {
alert( "User clicked on 'foo.'" );
});
The problem of your code is that there isn't a on event.
ref http://api.jquery.com/category/events/mouse-events/
If ctl00_btnSearch001 is a correct id for what ever you are trying to click. Try changing it to this:
(function ($){
$(document).on("click", "#ctl00_btnSearch001", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
I'm trying to get to work a remote content for bootstrap 3 popover and I cant get the content to show.
My html:
<a class="btn-link mchat-link hidden-xs rule" href="javascript:void(0)" id="oneData" data-toggle="popover" title="{L__HELP}" data-remote="{T_SUPER_TEMPLATE_PATH}/the_rules.html" title="{L_HELP}" value="{L_HELP}"><i class="icon-moon-question"></i></a>
my js:
$('#oneData').popover({placement:'top', html:true});
what am I missing been trying this for hours and no success
There is no data-remote attribute for Bootstrap popover, but we can use it like this to load remote data into a Popover:
html
link
js
$('*[data-remote]').on('mouseover', function() {
var el = $(this);
$.get(el.data('remote'),function(html) {
el.popover({
content: html,
html : true,
placement: 'right'
});
el.popover('show');
});
});
I needed the popover to stay open until the user hovers out of the link or out of the popover so I added some magic to do just that
js (with stay open functionality)
$('*[data-remote]').on('mouseover', function() {
var el = $(this);
$.get(el.data('remote'),function(html) {
el.popover({
content: html,
html : true,
placement: 'right'
});
el.popover('show');
$(".popover").on("mouseleave", function() {
var el = $(this);
el.popover('hide');
});
el.popover().on("mouseleave", function() {
var el = $(this);
setTimeout(function() {
if (!$(".popover:hover").length) {
el.popover("hide")
}
}, 300);
});
});
});
I currently have a bootstrap popover holding a button. The popover shows only when the mouse is over a table's tr.
What I want to do is to be able to access the elements for that row, is this possible.
Popover code:
$('.popup').popover(
{
placement: 'top',
trigger: 'manual',
delay: { show: 350, hide: 100 },
html: true,
content: $('#shortcuts').html(),
title: "Quick Tasks"
}
).parent().delegate('#quickDeleteBtn', 'click', function() {
alert($(this).closest('tr').children('td').text()); // ???
});
var timer,
popover_parent;
function hidePopover(elem) {
$(elem).popover('hide');
}
$('.popup').hover(
function() {
var self = this;
clearTimeout(timer);
$('.popover').hide(); //Hide any open popovers on other elements.
popover_parent = self
//$('.popup').attr("data-content","WOOHOOOO!");
$(self).popover('show');
},
function() {
var self = this;
timer = setTimeout(function(){hidePopover(self)},250);
});
$(document).on({
mouseenter: function() {
clearTimeout(timer);
},
mouseleave: function() {
var self = this;
timer = setTimeout(function(){hidePopover(popover_parent)},250);
}
}, '.popover');
HTML:
<div class="hide" id="shortcuts">
Delete
</div>
javascript that implements popover on row:
rows += '<tr class="popup datarow" rel="popover">';
Does anyone know what I'm doing wrong here and how I am supposed to access the child elements of the tr I'm hovering over?
JSFiddle: http://jsfiddle.net/C5BjY/8/
For some reason I couldn't get closest() to work as it should. Using parent().parent() to get to the containing .popover divider, then using prev() to get the previous tr element seems to do the trick however.
Just change:
alert($(this).closest('tr').children('td').text());
To:
alert($(this).parent().parent().prev('tr').children('td').text());
JSFiddle example.
As a side note, as your Fiddle uses jQuery 1.10.1 you should change delegate() to on():
on('click', '#quickDeleteBtn', function(index) { ... });
Here I have fixed it.
You just have to pass the container option in which the popover element is added for the popover
$('.popup').each(function (index) {
console.log(index + ": " + $(this).text());
$(this).popover({
placement: 'top',
trigger: 'manual',
delay: {
show: 350,
hide: 100
},
html: true,
content: $('#shortcuts').html(),
title: "Quick Tasks",
container: '#' + this.id
});
});
In your button click alert, $(this) refers to the button itself. In the DOM hierarchy, the popover html is nowhere near your hovered tr.
Add a handler to the list item to store itself in a global variable and access that from the click event. See the forked fiddle here.
First we declare a global (at the very top):
var hovered;
Then we add a mouseover handler to the list item. Note that using 'on' means every newly generated list item will also receive this handler:
$('body').on('mouseover', '.popup', function() {
hovered = $(this);
});
Then we can alert the needed data from within the button click event:
alert(hovered.text());
See here JS Fiddle
by removing the delegate and using the id to find the button and attaching it to a click handler by making the popover makes it easier to track it
$(self).popover('show');
$('#quickDeleteBtn').click(function(){
alert($(self).text());
});
also note
$('#shortcuts').remove();
because you were using the button in the popover with the same ID in the #shortcuts we couldn't select it first, now we remove it we can
You already have the correct element in your code. Just reuse the popover_parent variable and you are all set :) FIDDLE
alert($(popover_parent).text());
Or you could do something around like this :
$('.popup').hover(
function () {
var self = this;
clearTimeout(timer);
$('.popover').hide(); //Hide any open popovers on other elements.
$('#quickDeleteBtn').data('target', '');
popover_parent = self;
//$('.popup').attr("data-content","WOOHOOOO!");
$('#quickDeleteBtn').data('target', $(self));
$(self).popover('show');
},
function () {
var self = this;
timer = setTimeout(function () {
$('#quickDeleteBtn').data('target', '');
hidePopover(self)
}, 250);
});
$(document).on({
mouseenter: function () {
clearTimeout(timer);
},
mouseleave: function () {
var self = this;
timer = setTimeout(function () {
$('#quickDeleteBtn').data('target', '');
hidePopover(popover_parent)
}, 250);
}
}, '.popover');
I just store the element clicked in your #quickDeleteBtn then use the link.
FIDDLE HERE
I'm currently using popovers with Twitter Bootstrap, initiated like this:
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).click(function(e) {
$(this).popover('toggle');
e.preventDefault();
});
As you can see, they're triggered manually, and clicking on .popup-marker (which is a div with a background image) toggles a popover. This works great, but I'd like to also be able to close the popover with a click anywhere else on the page (but not on the popover itself!).
I've tried a few different things, including the following, but with no results to show for it:
$('body').click(function(e) {
$('.popup-marker').popover('hide');
});
How can I close the popover with a click anywhere else on the page, but not with a click onthe popover itself?
Presuming that only one popover can be visible at any time, you can use a set of flags to mark when there's a popover visible, and only then hide them.
If you set the event listener on the document body, it will trigger when you click the element marked with 'popup-marker'. So you'll have to call stopPropagation() on the event object. And apply the same trick when clicking on the popover itself.
Below is a working JavaScript code that does this. It uses jQuery >= 1.7
jQuery(function() {
var isVisible = false;
var hideAllPopovers = function() {
$('.popup-marker').each(function() {
$(this).popover('hide');
});
};
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).on('click', function(e) {
// if any other popovers are visible, hide them
if(isVisible) {
hideAllPopovers();
}
$(this).popover('show');
// handle clicking on the popover itself
$('.popover').off('click').on('click', function(e) {
e.stopPropagation(); // prevent event for bubbling up => will not get caught with document.onclick
});
isVisible = true;
e.stopPropagation();
});
$(document).on('click', function(e) {
hideAllPopovers();
isVisible = false;
});
});
http://jsfiddle.net/AFffL/539/
The only caveat is that you won't be able to open 2 popovers at the same time. But I think that would be confusing for the user, anyway :-)
This is even easier :
$('html').click(function(e) {
$('.popup-marker').popover('hide');
});
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).click(function(e) {
$(this).popover('toggle');
e.stopPropagation();
});
I had a similar need, and found this great little extension of the Twitter Bootstrap Popover by Lee Carmichael, called BootstrapX - clickover. He also has some usage examples here. Basically it will change the popover into an interactive component which will close when you click elsewhere on the page, or on a close button within the popover. This will also allow multiple popovers open at once and a bunch of other nice features.
Plugin can be found here.
Usage example
<button rel="clickover" data-content="Show something here.
<button data-dismiss='clickover'
>Close Clickover</button>"
>Show clickover</button>
javascript:
// load click overs using 'rel' attribute
$('[rel="clickover"]').clickover();
The accepted solution gave me some issues (clicking on the '.popup-marker' element of the opened popover made the popovers not work afterwards). I came up with this other solution that works perfectly for me and it's quite simple (I'm using Bootstrap 2.3.1):
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).click(function(e) {
$('.popup-marker').not(this).popover('hide');
$(this).popover('toggle');
});
$(document).click(function(e) {
if (!$(e.target).is('.popup-marker, .popover-title, .popover-content')) {
$('.popup-marker').popover('hide');
}
});
UPDATE: This code works with Bootstrap 3 as well!
read "Dismiss on next click"
here http://getbootstrap.com/javascript/#popovers
You can use the focus trigger to dismiss popovers on the next click, but you have to use use the <a> tag, not the <button> tag, and you also must include a tabindex attribute...
Example:
<a href="#" tabindex="0" class="btn btn-lg btn-danger"
data-toggle="popover" data-trigger="focus" title="Dismissible popover"
data-content="And here's some amazing content. It's very engaging. Right?">
Dismissible popover
</a>
All of the existing answers are fairly weak, as they rely on capturing all document events then finding active popovers, or modifying the call to .popover().
A much better approach is to listen for show.bs.popover events on the document's body then react accordingly. Below is code which will close popovers when the document is clicked or esc is pressed, only binding event listeners when popovers are shown:
function closePopoversOnDocumentEvents() {
var visiblePopovers = [];
var $body = $("body");
function hideVisiblePopovers() {
$.each(visiblePopovers, function() {
$(this).popover("hide");
});
}
function onBodyClick(event) {
if (event.isDefaultPrevented())
return;
var $target = $(event.target);
if ($target.data("bs.popover"))
return;
if ($target.parents(".popover").length)
return;
hideVisiblePopovers();
}
function onBodyKeyup(event) {
if (event.isDefaultPrevented())
return;
if (event.keyCode != 27) // esc
return;
hideVisiblePopovers();
event.preventDefault();
}
function onPopoverShow(event) {
if (!visiblePopovers.length) {
$body.on("click", onBodyClick);
$body.on("keyup", onBodyKeyup);
}
visiblePopovers.push(event.target);
}
function onPopoverHide(event) {
var target = event.target;
var index = visiblePopovers.indexOf(target);
if (index > -1) {
visiblePopovers.splice(index, 1);
}
if (visiblePopovers.length == 0) {
$body.off("click", onBodyClick);
$body.off("keyup", onBodyKeyup);
}
}
$body.on("show.bs.popover", onPopoverShow);
$body.on("hide.bs.popover", onPopoverHide);
}
https://github.com/lecar-red/bootstrapx-clickover
It's an extension of twitter bootstrap popover and will solve the problem very simply.
For some reason none of the other solutions here worked for me. However, after a lot of troubleshooting, I finally arrived at this method which works perfectly (for me at least).
$('html').click(function(e) {
if( !$(e.target).parents().hasClass('popover') ) {
$('#popover_parent').popover('destroy');
}
});
In my case I was adding a popover to a table and absolutely positioning it above/below the td that was clicked. The table selection was handled by jQuery-UI Selectable so I'm not sure if that was interfering. However whenever I clicked inside the popover my click handler which targeted $('.popover') never worked and the event handling was always delegated to the $(html) click handler. I'm fairly new to JS so perhaps I'm just missing something?
Anyways I hope this helps someone!
I give all my popovers anchors the class activate_popover. I activate them all at once onload
$('body').popover({selector: '.activate-popover', html : true, container: 'body'})
to get the click away functionality working I use (in coffee script):
$(document).on('click', (e) ->
clickedOnActivate = ($(e.target).parents().hasClass("activate-popover") || $(e.target).hasClass("activate-popover"))
clickedAway = !($(e.target).parents().hasClass("popover") || $(e.target).hasClass("popover"))
if clickedAway && !clickedOnActivate
$(".popover.in").prev().popover('hide')
if clickedOnActivate
$(".popover.in").prev().each () ->
if !$(this).is($(e.target).closest('.activate-popover'))
$(this).popover('hide')
)
Which works perfectly fine with bootstrap 2.3.1
Even though there are a lot of solutions here, i'd like to propose mine as well, i don't know if there is some solution up there that solves it all, but i tried 3 of them and they had issues, like clicking on the popover it self makes it hide, others that if i had another popover buttons clicked both/multiple popovers would still appear (like in the selected solution), How ever, This one fixed it all
var curr_popover_btn = null;
// Hide popovers function
function hide_popovers(e)
{
var container = $(".popover.in");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
if( curr_popover_btn != null )
{
$(curr_popover_btn).popover('hide');
curr_popover_btn = null;
}
container.hide();
}
}
// Hide popovers when out of focus
$('html').click(function(e) {
hide_popovers(e);
});
$('.popover-marker').popover({
trigger: 'manual'
}).click(function(e) {
hide_popovers(e);
var $popover_btns = $('.popover-marker');
curr_popover_btn = this;
var $other_popover_btns = jQuery.grep($($popover_btns), function(popover_btn){
return ( popover_btn !== curr_popover_btn );
});
$($other_popover_btns).popover('hide');
$(this).popover('toggle');
e.stopPropagation();
});
I would set the focus to the newly created pop-over and remove it on blur. That way it's not needed to check which element of the DOM has been clicked and the pop-over can be clicked, and selected too: it will not lose its focus and will not disappear.
The code:
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).click(function(e) {
$(this).popover('toggle');
// set the focus on the popover itself
jQuery(".popover").attr("tabindex",-1).focus();
e.preventDefault();
});
// live event, will delete the popover by clicking any part of the page
$('body').on('blur','.popover',function(){
$('.popup-marker').popover('hide');
});
Here is the solution which worked very fine for me, if it can help :
/**
* Add the equals method to the jquery objects
*/
$.fn.equals = function(compareTo) {
if (!compareTo || this.length !== compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
/**
* Activate popover message for all concerned fields
*/
var popoverOpened = null;
$(function() {
$('span.btn').popover();
$('span.btn').unbind("click");
$('span.btn').bind("click", function(e) {
e.stopPropagation();
if($(this).equals(popoverOpened)) return;
if(popoverOpened !== null) {
popoverOpened.popover("hide");
}
$(this).popover('show');
popoverOpened = $(this);
e.preventDefault();
});
$(document).click(function(e) {
if(popoverOpened !== null) {
popoverOpened.popover("hide");
popoverOpened = null;
}
});
});
Here's my solution, for what it's worth:
// Listen for clicks or touches on the page
$("html").on("click.popover.data-api touchend.popover.data-api", function(e) {
// Loop through each popover on the page
$("[data-toggle=popover]").each(function() {
// Hide this popover if it's visible and if the user clicked outside of it
if ($(this).next('div.popover:visible').length && $(".popover").has(e.target).length === 0) {
$(this).popover("hide");
}
});
});
I had some problem to get it working on bootstrap 2.3.2.
But i sloved it this way:
$(function () {
$(document).mouseup(function (e) {
if(($('.popover').length > 0) && !$(e.target).hasClass('popInfo')) {
$('.popover').each(function(){
$(this).prev('.popInfo').popover('hide');
});
}
});
$('.popInfo').popover({
trigger: 'click',
html: true
});
});
tweaked #David Wolever solution slightly:
function closePopoversOnDocumentEvents() {
var visiblePopovers = [];
var $body = $("body");
function hideVisiblePopovers() {
/* this was giving problems and had a bit of overhead
$.each(visiblePopovers, function() {
$(this).popover("hide");
});
*/
while (visiblePopovers.length !== 0) {
$(visiblePopovers.pop()).popover("hide");
}
}
function onBodyClick(event) {
if (event.isDefaultPrevented())
return;
var $target = $(event.target);
if ($target.data("bs.popover"))
return;
if ($target.parents(".popover").length)
return;
hideVisiblePopovers();
}
function onBodyKeyup(event) {
if (event.isDefaultPrevented())
return;
if (event.keyCode != 27) // esc
return;
hideVisiblePopovers();
event.preventDefault();
}
function onPopoverShow(event) {
if (!visiblePopovers.length) {
$body.on("click", onBodyClick);
$body.on("keyup", onBodyKeyup);
}
visiblePopovers.push(event.target);
}
function onPopoverHide(event) {
var target = event.target;
var index = visiblePopovers.indexOf(target);
if (index > -1) {
visiblePopovers.splice(index, 1);
}
if (visiblePopovers.length == 0) {
$body.off("click", onBodyClick);
$body.off("keyup", onBodyKeyup);
}
}
$body.on("show.bs.popover", onPopoverShow);
$body.on("hide.bs.popover", onPopoverHide);
}
This question was also asked here and my answer provides not only a way to understand jQuery DOM traversal methods but 2 options for handling the closing of popovers by clicking outside.
Open multiple popovers at once or one popover at a time.
Plus these small code snippets can handle the closing of buttons containing icons!
https://stackoverflow.com/a/14857326/1060487
This one works like a charm and I use it.
It will open the popover when you click and if you click again it will close, also if you click outside of the popover the popover will be closed.
This also works with more than 1 popover.
function hideAllPopovers(){
$('[data-toggle="popover"]').each(function() {
if ($(this).data("showing") == "true"){
$(this).data("showing", "false");
$(this).popover('hide');
}
});
}
$('[data-toggle="popover"]').each(function() {
$(this).popover({
html: true,
trigger: 'manual'
}).click(function(e) {
if ($(this).data("showing") != "true"){
hideAllPopovers();
$(this).data("showing", "true");
$(this).popover('show');
}else{
hideAllPopovers();
}
e.stopPropagation();
});
});
$(document).click(function(e) {
hideAllPopovers();
});
Another solution, it covered the problem I had with clicking descendants of the popover:
$(document).mouseup(function (e) {
// The target is not popover or popover descendants
if (!$(".popover").is(e.target) && 0 === $(".popover").has(e.target).length) {
$("[data-toggle=popover]").popover('hide');
}
});
I do it as below
$("a[rel=popover]").click(function(event){
if(event.which == 1)
{
$thisPopOver = $(this);
$thisPopOver.popover('toggle');
$thisPopOver.parent("li").click(function(event){
event.stopPropagation();
$("html").click(function(){
$thisPopOver.popover('hide');
});
});
}
});
Hope this helps!
If you're trying to use twitter bootstrap popover with pjax, this worked for me:
App.Utils.Popover = {
enableAll: function() {
$('.pk-popover').popover(
{
trigger: 'click',
html : true,
container: 'body',
placement: 'right',
}
);
},
bindDocumentClickEvent: function(documentObj) {
$(documentObj).click(function(event) {
if( !$(event.target).hasClass('pk-popover') ) {
$('.pk-popover').popover('hide');
}
});
}
};
$(document).on('ready pjax:end', function() {
App.Utils.Popover.enableAll();
App.Utils.Popover.bindDocumentClickEvent(this);
});
#RayOnAir, I have same issue with previous solutions. I come close to #RayOnAir solution too. One thing that improved is close already opened popover when click on other popover marker. So my code is:
var clicked_popover_marker = null;
var popover_marker = '#pricing i';
$(popover_marker).popover({
html: true,
trigger: 'manual'
}).click(function (e) {
clicked_popover_marker = this;
$(popover_marker).not(clicked_popover_marker).popover('hide');
$(clicked_popover_marker).popover('toggle');
});
$(document).click(function (e) {
if (e.target != clicked_popover_marker) {
$(popover_marker).popover('hide');
clicked_popover_marker = null;
}
});
I found this to be a modified solution of pbaron's suggestion above, because his solution activated the popover('hide') on all elements with class 'popup-marker'. However, when you're using popover() for html content instead of the data-content, as I'm doing below, any clicks inside that html popup actually activate the popover('hide'), which promptly closes the window. This method below iterates through each .popup-marker element and discovers first if the parent is related to the .popup-marker's id that was clicked, and if so then does not hide it. All other divs are hidden...
$(function(){
$('html').click(function(e) {
// this is my departure from pbaron's code above
// $('.popup-marker').popover('hide');
$('.popup-marker').each(function() {
if ($(e.target).parents().children('.popup-marker').attr('id')!=($(this).attr('id'))) {
$(this).popover('hide');
}
});
});
$('.popup-marker').popover({
html: true,
// this is where I'm setting the html for content from a nearby hidden div with id="html-"+clicked_div_id
content: function() { return $('#html-'+$(this).attr('id')).html(); },
trigger: 'manual'
}).click(function(e) {
$(this).popover('toggle');
e.stopPropagation();
});
});
I came up with this:
My scenario included more popovers on the same page, and hiding them just made them invisible and because of that, clicking on items behind the popover was not possible.
The idea is to mark the specific popover-link as 'active' and then you can simply 'toggle' the active popover. Doing so will close the popover completely.
$('.popover-link').popover({ html : true, container: 'body' })
$('.popover-link').popover().on 'shown.bs.popover', ->
$(this).addClass('toggled')
$('.popover-link').popover().on 'hidden.bs.popover', ->
$(this).removeClass('toggled')
$("body").on "click", (e) ->
$openedPopoverLink = $(".popover-link.toggled")
if $openedPopoverLink.has(e.target).length == 0
$openedPopoverLink.popover "toggle"
$openedPopoverLink.removeClass "toggled"
I was trying to make a simple solution for a simple issue. Above posts are good but so complicated for a simple issue. So i made a simple thing. Just added a close button. Its perfect for me.
$(".popover-link").click(function(){
$(".mypopover").hide();
$(this).parent().find(".mypopover").show();
})
$('.close').click(function(){
$(this).parents('.mypopover').css('display','none');
});
<div class="popover-content">
<i class="fa fa-times close"></i>
<h3 class="popover-title">Title here</h3>
your other content here
</div>
.popover-content {
position:relative;
}
.close {
position:absolute;
color:#CCC;
right:5px;
top:5px;
cursor:pointer;
}
I like this, simple yet effective..
var openPopup;
$('[data-toggle="popover"]').on('click',function(){
if(openPopup){
$(openPopup).popover('hide');
}
openPopup=this;
});
Add btn-popover class to your popover button/link that opens the popover. This code will close the popovers when clicking outside of it.
$('body').on('click', function(event) {
if (!$(event.target).closest('.btn-popover, .popover').length) {
$('.popover').popover('hide');
}
});
An even easier solution, just iterate through all popovers and hide if not this.
$(document).on('click', '.popup-marker', function() {
$(this).popover('toggle')
})
$(document).bind('click touchstart', function(e) {
var target = $(e.target)[0];
$('.popup-marker').each(function () {
// hide any open popovers except for the one we've clicked
if (!$(this).is(target)) {
$(this).popover('hide');
}
});
});
$('.popForm').popover();
$('.conteneurPopForm').on("click",".fermePopover",function(){
$(".popForm").trigger("click");
});
To be clear, just trigger the popover
This should work in Bootstrap 4:
$("#my-popover-trigger").popover({
template: '<div class="popover my-popover-content" role="tooltip"><div class="arrow"></div><div class="popover-body"></div></div>',
trigger: "manual"
})
$(document).click(function(e) {
if ($(e.target).closest($("#my-popover-trigger")).length > 0) {
$("#my-popover-trigger").popover("toggle")
} else if (!$(e.target).closest($(".my-popover-content")).length > 0) {
$("#my-popover-trigger").popover("hide")
}
})
Explanation:
The first section inits the popover as per the docs: https://getbootstrap.com/docs/4.0/components/popovers/
The first "if" in the second section checks whether the clicked element is a descendant of #my-popover-trigger. If that is true, it toggles the popover (it handles the click on the trigger).
The second "if" in the second section checks whether the clicked element is a descendant of the popover content class which was defined in the init template. If it is not this means that the click was not inside the popover content, and the popover can be hidden.
Try data-trigger="focus" instead of "click".
This solved the problem for me.
I have a link that uses the Twitter Bootstrap Popover version 1.3.0 to show some information. This information includes a link, but every-time I move my mouse from the link to the popover, the popover just disappears.
How can I hold popover open long enough to enable the mouse to move into it? Then when the mouse moves out of the link and popover, hide it?
Or is there some other plugin that can do this?
With bootstrap (tested with version 2) I figured out the following code:
$("a[rel=popover]")
.popover({
offset: 10,
trigger: 'manual',
animate: false,
html: true,
placement: 'left',
template: '<div class="popover" onmouseover="$(this).mouseleave(function() {$(this).hide(); });"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
}).click(function(e) {
e.preventDefault() ;
}).mouseenter(function(e) {
$(this).popover('show');
});
The main point is to override template with mouseleave() enabler. I hope this helps.
Bootstrap 3 and above
Simple, just use the container option and have it as the element that is calling the popover. This way, the popover is a child of the element that calls it. Hence, you are technically still hovering over the parent, because the child popover belongs to it.
For example:
HTML:
<div class="pop" data-content="Testing 12345">This has a popover</div>
<div class="pop" data-content="Testing 12345">This has a popover</div>
<div class="pop" data-content="Testing 12345">This has a popover</div>
jQuery:
Running an $.each() loop over every one of my elements that I want a popover binded to its parent. In this case, each element has the class of pop.
$('.pop').each(function () {
var $elem = $(this);
$elem.popover({
placement: 'top',
trigger: 'hover',
html: true,
container: $elem
});
});
CSS:
This part is optional, but recommended. It moves the popover down by 7 pixels for easier access.
.pop .popover {
margin-top:7px;
}
WORKING DEMO
Just to add to Marchello's example, if you want the popover to disappear if the user moves their mouse away from the popover and source link, try this out.
var timeoutObj;
$('.nav_item a').popover({
offset: 10,
trigger: 'manual',
html: true,
placement: 'right',
template: '<div class="popover" onmouseover="clearTimeout(timeoutObj);$(this).mouseleave(function() {$(this).hide();});"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
}).mouseenter(function(e) {
$(this).popover('show');
}).mouseleave(function(e) {
var ref = $(this);
timeoutObj = setTimeout(function(){
ref.popover('hide');
}, 50);
});
This is a little hacky, but building off of marchello's example, I did this (no need for template):
$(".trigger-link").popover({
trigger: "manual",
}).on("click", function(e) {
e.preventDefault();
}).on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(this).siblings(".popover").on("mouseleave", function() {
$(_this).popover('hide');
});
}).on("mouseleave", function() {
var _this = this;
setTimeout(function() {
if (!$(".popover:hover").length) {
$(_this).popover("hide")
}
}, 100);
});
The setTimeout helps ensure that there's time to travel from the trigger link to the popover.
This issue on the bootstrap github repo deals with this problem. fat pointed out the experimental "in top/bottom/left/right" placement. It works, pretty well, but you have to make sure the popover trigger is not positioned statically with css. Otherwise the popover won't appear where you want it to.
HTML:
<span class="myClass" data-content="lorem ipsum content" data-original-title="pop-title">Hover me to show a popover.</span>
CSS:
/*CSS */
.myClass{ position: relative;}
JS:
$(function(){
$('.myClass').popover({placement: 'in top'});
});
Solution worked for us for Bootstrap 3.
var timeoutObj;
$('.list-group a').popover({
offset: 10,
trigger: 'manual',
html: true,
placement: 'right',
template: '<div class="popover" onmouseover="$(this).mouseleave(function() {$(this).hide();});"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
}).mouseenter(function(e) {
$(this).popover('show');
}).mouseleave(function(e) {
var _this = this;
setTimeout(function() {
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
}, 100);
});
Here's my take: http://jsfiddle.net/WojtekKruszewski/Zf3m7/22/
Sometimes while moving mouse from popover trigger to actual popover content diagonally, you hover over elements below. I wanted to handle such situations – as long as you reach popover content before the timeout fires, you're save (the popover won't disappear). It requires delay option.
This hack basically overrides Popover leave function, but calls the original (which starts timer to hide the popover). Then it attaches a one-off listener to mouseenter popover content element's.
If mouse enters the popover, the timer is cleared. Then it turns it listens to mouseleave on popover and if it's triggered, it calls the original leave function so that it could start hide timer.
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
var container, timeout;
originalLeave.call(this, obj);
if(obj.currentTarget) {
container = $(obj.currentTarget).siblings('.popover')
timeout = self.timeout;
container.one('mouseenter', function(){
//We entered the actual popover – call off the dogs
clearTimeout(timeout);
//Let's monitor popover content instead
container.one('mouseleave', function(){
$.fn.popover.Constructor.prototype.leave.call(self, self);
});
})
}
};
Finally I fix this problem. Popover disappear is because Popover not child node of link, it is child node of body.
So fix it is easy, change bootstrap-twipsy.js content:
change .prependTo(document.body) to .prependTo(this.$element)
and fix position problem cause by change.
and some use link tiger popover will cause popover with link too, so add a span contain link, so problem solved.
This is a version of Wojtek Kruszewski solution. This version handle popover blink when mouse go back to trigger. http://jsfiddle.net/danielgatis/QtcpD/
(function($) {
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj) {
var self = (obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type));
originalLeave.call(this, obj);
if (obj.currentTarget) {
var current = $(obj.currentTarget);
var container = current.siblings(".popover");
container.on("mouseenter", function() {
clearTimeout(self.timeout);
});
container.on("mouseleave", function() {
originalLeave.call(self, self);
});
}
};
var originalEnter = $.fn.popover.Constructor.prototype.enter;
$.fn.popover.Constructor.prototype.enter = function(obj) {
var self = (obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type));
clearTimeout(self.timeout);
if (!$(obj.currentTarget).siblings(".popover:visible").length) {
originalEnter.call(this, obj);
}
};
})(jQuery);
I tried the solutions from #Wotjek Kruszewski and #danielgatis, but neither worked for me. Caveat: I'm using Bootstrap v2.1.0, not v3. This solution is in coffeescript (why are people still using plain javascript? =)).
(($) ->
originalLeave = $.fn.popover.Constructor::leave
$.fn.popover.Constructor::leave = (e) ->
self = $(e.currentTarget)[#type](#_options).data(#type)
originalLeave.call #, e
if e.currentTarget
container = $(".popover")
container.one "mouseenter", ->
clearTimeout self.timeout
container.one "mouseleave", ->
originalLeave.call self, e
) jQuery
Here is what i did:
e = $("a[rel=popover]")
e.popover({
content: d,
html:true,
trigger:'hover',
delay: {hide: 500},
placement: 'bottom',
container: e,
})
This is a very simple and awesone solution to this probelm, which i found out by looking into the bootstrap tooltip code. In Bootstrap v3.0.3 here is the line of code i noticed:
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this says that if container property of popover is defined then the popover gets appendTo() the element instead of insertAfter() the original element, all you need to do is just pass the element as container property. Because of appendTo() the popover becomes part of the link on which the hover event was binded and thus keeps the popover open when mouse moves on it.
This works for me on BootStrap 3:
el.popover({
delay: {hide: 100}
}).on("shown.bs.popover", function(){
el.data("bs.popover").tip().off("mouseleave").on("mouseleave", function(){
setTimeout(function(){
el.popover("hide");
}, 100);
});
}).on("hide.bs.popover", function(ev){
if(el.data("bs.popover").tip().is(":hover"))
ev.preventDefault();
});
At the end of the conversation linked by #stevendaniels is a link to a Twitter Bootstrap extension called BootstrapX - clickover by Lee Carmichael. This changes the popover from an overlarge tooltip into an interactive control, which can be closed by clicking elsewhere on the form, a close button, or after a timeout. Its easy to use, and worked very well for the project I needed it in. Some examples of its usage can be found here.
I didn't like any of the answers I've found, so I combined some answers that were close to make the following code. It allows you to end up just typing $(selector).pinnablepopover(options); every time you want to make a 'pinnable' popover.
Code that makes things easy:
$.fn.popoverHoverShow = function ()
{
if(this.data('state') !== 'pinned')
{
if(!this.data('bs.popover').$tip || (this.data('bs.popover').$tip && this.data('bs.popover').$tip.is(':hidden')))
{
this.popover('show');
}
}
};
$.fn.popoverHoverHide = function ()
{
if (this.data('state') !== 'pinned')
{
var ref = this;
this.data('bs.popover').$tip.data('timeout', setTimeout(function(){ ref.popover('hide') }, 100))
.on('mouseenter', function(){ clearTimeout($(this).data('timeout')) })
.on('mouseleave', function(){ $(this).data('timeout', setTimeout(function(){ ref.popover('hide') }, 100)) });
this.on('mouseenter', function(){ clearTimeout($(this).data('timeout')) });
}
};
$.fn.popoverClickToggle = function ()
{
if (this.data('state') !== 'pinned')
{
this.data('state', 'pinned');
}
else
{
this.data('state', 'hover')
}
};
$.fn.pinnablepopover = function (options)
{
options.trigger = manual;
this.popover(options)
.on('mouseenter', function(){ $(this).popoverHoverShow() })
.on('mouseleave', function(){ $(this).popoverHoverHide() })
.on('click', function(){ $(this).popoverClickToggle() });
};
Example usage:
$('[data-toggle=popover]').pinnablepopover({html: true, container: 'body'});
After seeing all Answer I made this I think it will be helpful .You Can manage Everything which you need.
Many answer doesn't make show delay I use this. Its work very nice in my project
/******
/*************************************************************/
<div class='thumbnail' data-original-title='' style='width:50%'>
<div id='item_details' class='popper-content hide'>
<div>
<div style='height:10px'> </div>
<div class='title'>Bad blood </div>
<div class='catagory'>Music </div>
</div>
</div>
HELLO POPOVER
</div>"
/****************SCRIPT CODE ****************** PLEASE USE FROM HEAR ******/
$(".thumbnail").popover({
trigger: "manual" ,
html: true,
animation:true,
container: 'body',
placement: 'auto right',
content: function () {
return $(this).children('.popper-content').html();
}}) .on("mouseenter", function () {
var _this = this;
$('.thumbnail').each(function () {
$(this).popover('hide');
});
setTimeout(function(){
if ($(_this).is(':hover')) {
$(_this).popover("show");
}
},1000);
$(".popover").on("mouseleave", function () {
$('.thumbnail').each(function () {
$(this).popover('hide');
});
$(_this).popover('hide');
}); }).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
}, 100); });
Now I just switch to webuiPopover, it just works.