I have a function which creates popovers in my page, retrieving the content from an AJAX call. During the creation my function changes the popover position (it is page-wide, so I set to 0 the left
attribute and move the arrow to point to my element). Everything works fine the first time, but if I move the mouse out and then in again the popover doesn't move from its default position (and neither does the arrow)
My code:
var last_opened_popover = null
jQuery(document).ready(function(){
jQuery("*[data-poload]").mouseenter(function(){
if (last_opened_popover != null){
last_opened_popover.popover("destroy")
}
var element = jQuery(this)
last_opened_popover = element
var polId = element.data("poload")
jQuery.ajax({
url : my_url,
type : "POST",
data : {
//datas
},
success : function(result){
var supporter_list = compose_supporter_list(result);
var left = element.position().left + 75
element.popover({
content : supporter_list,
html : true,
placement : "bottom",
template : '<div id="shown-popover" class="popover pgsc-popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
element.popover("show")
var popover = jQuery("#shown-popover")
popover.css("left", 0)
popover.find(".arrow").css("left", left)
}
})
}).mouseleave(function(){
jQuery(this).popover("destroy")
})
})
The problem was that all the generated popover shared the same ID. Even if I destroied each one before creating another, the ID is somehow retained, so jQuery cannot access the new elements. The solution is to simply generate new IDs to make sure no popover share the same ID, I did it by simply using a counter:
var last_opened_popover = null
var popover_counter = 0
jQuery(document).ready(function(){
jQuery("*[data-poload]").mouseenter(function(){
if (last_opened_popover != null){
last_opened_popover.popover("destroy")
}
var element = jQuery(this)
last_opened_popover = element
var polId = element.data("poload")
jQuery.ajax({
url : my_url,
type : "POST",
data : {
//datas
},
success : function(result){
var supporter_list = compose_supporter_list(result);
var left = element.position().left + 75
element.popover({
content : supporter_list,
html : true,
placement : "bottom",
template : '<div id="shown-popover-' + popover_counter + '" class="popover pgsc-popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
element.popover("show")
var popover = jQuery("#shown-popover-" + popover_counter)
popover.css("left", 0)
popover.find(".arrow").css("left", left)
popover_counter++
}
})
})