Note: I understand there's a bug in bootstrap that causes popovers/tooltips to call the content function() twice, but I do not think that is the case here.
I am using bootstrap popovers in conjunction with the FullCalendar gem to update events.
Inside the popover, there're multiple divs that get hidden/shown depending on which view the user is on (i.e. there is a view for displaying the event info and another for updating the view). The way I'm handling this is by using addClass('hide') and removeClass('hide'), so correct me if this is improper.
When I click on an event, it displays the popover with the content added it to once (good). When I navigate to the update div inside the popover and send an .ajax({type: 'PUT'}), the popover for the updated event displays two of the content divs (bad); however, this happens randomly.
If I reload the entire DOM and redo the process over and over again, this duplication happens ~half the time.
When popover is clicked just after DOM loads (good)
When popover is clicked after ajax PUT is called, this SOMETIMES HAPPENS (even if no fields are changed)
Here's how I send the .ajax request:
// SAVE button for LESSONS, POPOVER ***/
$('body').on('click', 'button.popover-lesson-save', function() {
var title = $('.popover input.popover-lesson-title').val();
var note = $('.popover input.popover-lesson-note').val();
// Retrieve event data from popover
var idStr = $('.popover div.popover-body').data('id');
var id = parseInt(idStr);
// Store event data into a hash for AJAX request and refetches events
var data = {
title: title,
note: note
};
// Make PUT AJAX request to database
$.ajax({
url: '/lessons/' + id,
type: 'PUT',
data: data,
dataType: 'json',
success: function(resp){
$('.popover div.popover-lessons-edit').addClass('hide');
$('.popover div.popover-lessons-view').removeClass('hide');
$('.popover').popover('hide');
$('#calendar').fullCalendar( 'refetchEvents' );
},
error: function(resp){
alert('Error code 2-502-1. Oops, something went wrong.');
}
});
});
And here is what I do in my FullCalendar callbacks:
// calendar options
$('#calendar').fullCalendar({
..
eventRender: function(calEvent, element, view){
if (typeof $(element).data('bs.popover') === 'undefined'){
// Find content html (append and clone prevents parent div from being overwritten)
var content = $("<div />").append($('.popover-lessons-content').clone());
var id = calEvent.id;
// Attach popover to html element
$(element).popover({
container: 'body',
placement: 'left',
html: true,
content: function(){
return content.html(); // This randomly duplicates
}
});
}
}
}
Something tells me that instead of append() here
var content = $("<div />").append($('.popover-lessons-content').clone());
you should use appendTo(). And yet not sure about purpose of clone() so I think it should look like as:
var content = $("<div />").appendTo('.popover-lessons-content');
and to avoid duplicates that $('.popover-lessons-content') thing should be cleared before appending to it.
Thanks to #c-smile, I've realised that the bug lied in how I retrieve my html template from my view file:
var content = $("<div />").append($('.popover-lessons-content').clone());
Instead, I should have done this (and this worked after much tinkering):
var content = $('.popover-lessons-content').html();
$(element).popover({
container: 'body',
placement: 'left',
html: true,
content: function(){
return content;
}
});
It takes the direct html instead of cloning the div and making a big mess.
Related
I can't find a solution for this plugin since I cannot find any working demo or documentation for external content via Ajax.
Basically I have a simple div with a mouse hover JS function:
<div onmouseover="myFunct(this,'.$comment['id'].');" >Hover Me</div>
And this is my JS function:
function myFunct(element, id){
$(element).tooltipster({
contentCloning: true,
interactive:true,
maxWidth:250,
contentAsHTML:true,
content: 'Loading...',
// 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section.
functionBefore: function(instance, helper) {
var $origin = $(helper.origin);
// we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens
if ($origin.data('loaded') !== true) {
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+id+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
// to remember that the data has been loaded
$origin.html('loaded', true);
}
});
}
}
});
}
Why the tooltip is shown only at the 2nd mouse hover?
Here is a similar Eg. JSFiddle
UPDATE
Thanks to the support this has solved my issue:
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
Anyway this doesn't work on Ajax dynamic content, and I don't know why (I tried to insert it on Ajax page, no way)
I'd recommend a few things: first, separate your JS from your HTML (this is considered best practice), second, initialize Tooltipster on page load, and last, remove the wrapper function. Once the tooltip is initialized your code will trigger by default on hover.
Separate JS from HTML
<div class="hover-me tool-tip" data-commentId="12345">Hover Me</div>
Initalize Tooltipster on Document Ready
$(document).ready(function() {
$('.tooltip').tooltipster();
});
Trigger Tooltipster with Hover
$('.hover-me').tooltipster({
// all of your code from above
functionBefore: function(){
var commentId = $(this).attr('data-commentId');
}
});
Note:
The default trigger for Tooltipster is hover (as seen in the documentation), however, you could explicitly set it by passing in trigger: hover, which would make your code slightly more readable and as such maintainable.
Tooltipster Support Recommendation (as seen in the comments)
I add this because it reinforces my solution above and adds context for future devs...that, and it might be overlooked in the comments section.
You initialize your tooltip when the mouseover event has already been fired, so Tooltipster cannot "hear" this first event and open the tooltip. You'd better initialize your tooltips at page load and put your comment id in a data-id attribute that you'll retrieve in functionBefore when you prepare your ajax call.
I'm paginating search results returned from an AJAX call with jScroll:
$('#search').keyup(function() {
var search = $(this).val();
$.get('/search', {search : search}, function(results) {
$('.scroll-table').html(results);
$('.scroll-table').jscroll();
});
});
After making a new search, when I scroll to the bottom, jScroll loads the content of the last href for the old search.
So if my old _nextHref was /search?query=A&page=3 and I enter B in the search field, instead of loading /search?query=B&page=2 from the new href, it will load /search?query=A&page=3 from the old href.
Apparently calling jscroll() from the ajax success function won't reconstruct it and _nextHref stays set to its old value. I tried destroying it before loading it, but it will keep it fom loading altogether:
$('#search').keyup(function() {
var search = $(this).val();
$('.scroll-table').jscroll.destroy();
$.get('/search', {search : search}, function(results) {
$('.scroll-table').html(results);
$('.scroll-table').jscroll(); /* now jScroll won't load at all */
});
});
Can you please give me an example how to reinitialize jScroll so it loads the new href?
I found a temporary solution by commenting out the following line:
// if (data && data.initialized) return;
This caused a further problem.. If the result list fits a single page (no pagination needed so there is no href on the first page, "Loading..." is displayed on the bottom of the list, because jScroll wanted to GET "/undefined" from the server. Here is how i fixed it:
// Initialization
if (_nextHref != 'undefined') {
$e.data('jscroll', $.extend({}, _data, {initialized: true, waiting: false, nextHref: _nextHref}));
_wrapInnerContent();
_preloadImage();
_setBindings();
} else {
_debug('warn', 'jScroll: nextSelector not found - destroying');
_destroy();
return false;
}
I don't know if there is a better way to do this, but now it works with AJAX calls as I expect it to work. If anyone knows of a proper way to reinitialize the plugin, please share it with us.
UPDATE: I created a proper fork of jScroll allowing it to be reinitialized on each AJAX load, preventing it from loading the old href, using:
$('.scroll').jscroll({
refresh: true
});
Hopefully this functionality gets merged in the main version.
If you don't want to patch jScroll, you can clear the jScroll data in your load (or get) callback:
var pane = $('#myInfiniteScroll');
pane.load(url, function() {
pane.data('jscroll', null);
pane.jscroll({
nextSelector: "link[rel='next']",
autoTrigger: true,
});
});
When you call the jscroll function, pass the same parameters as when you first initialized it (in this example, I defined two configuration parameters, but use what you need.). Better yet, factor that out into its own function so you don't end up duplicating code.
I have an element $('#anElement') with a potential popover attached, like
<div id="anElement" data-original-title="my title" data-trigger="manual" data-content="my content" rel="popover"></div>
I just would like to know how to check whether the popover is visible or not: how this can be accomplished with jQuery?
If this functionality is not built into the framework you are using (it's no longer twitter bootstrap, just bootstrap), then you'll have to inspect the HTML that is generated/modified to create this feature of bootstrap.
Take a look at the popupver documentation. There is a button there that you can use to see it in action. This is a great place to inspect the HTML elements that are at work behind the scene.
Crack open your chrome developers tools or firebug (of firefox) and take a look at what it happening. It looks like there is simply a <div> being inserted after the button -
<div class="popover fade right in" style="... />
All you would have to do is check for the existence of that element. Depending on how your markup is written, you could use something like this -
if ($("#popoverTrigger").next('div.popover:visible').length){
// popover is visible
}
#popoverTrigger is the element that triggered that popover to appear in the first place and as we noticed above, bootstrap simply appends the popover div after the element.
There is no method implemented explicitly in the boostrap popover plugin so you need to find a way around that. Here's a hack that will return true or false wheter the plugin is visible or not.
var isVisible = $('#anElement').data('bs.popover').tip().hasClass('in');
console.log(isVisible); // true or false
It accesses the data stored by the popover plugin which is in fact a Popover object, calls the object's tip() method which is responsible for fetching the tip element, and then checks if the element returned has the class in, which is indicative that the popover attached to that element is visible.
You should also check if there is a popover attached to make sure you can call the tip() method:
if ($('#anElement').data('bs.popover') instanceof Popover) {
// do your popover visibility check here
}
In the current version of Bootstrap, you can check whether your element has aria-describedby set. The value of the attribute is the id of the actual popover.
So for instance, if you want to change the content of the visible popover, you can do:
var popoverId = $('#myElement').attr('aria-describedby');
$('#myElement').next(popoverid, '.popover-content').html('my new content');
This checks if the given div is visible.
if ($('#div:visible').length > 0)
or
if ($('#div').is(':visible'))
Perhaps the most reliable option would be listening to shown/hidden events, as demonstrated below. This would eliminate the necessity of digging deep into the DOM that could be error prone.
var isMyPopoverVisible = false;//assuming popovers are hidden by default
$("#myPopoverElement").on('shown.bs.popover',function(){
isMyPopoverVisible = true;
});
$("#myPopoverElement").on('hidden.bs.popover',function(){
isMyPopoverVisible = false;
});
These events seem to be triggered even if you hide/show/toggle the popover programmatically, without user interaction.
P. S. tested with BS3.
Here is simple jQuery plugin to manage this. I've added few commented options to present different approaches of accessing objects and left uncommented that of my favor.
For current Bootstrap 4.0.0 you can take bundle with Popover.js: https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js
// jQuery plugins
(function($)
{
// Fired immiedately
$.fn.isPopover = function (options)
{
// Is popover?
// jQuery
//var result = $(this).hasAttr("data-toggle");
// Popover API
var result = !!$(this).data('bs.popover');
if (!options) return result;
var $tip = this.popoverTip();
if (result) switch (options)
{
case 'shown' :
result = $tip.is(':visible');
break;
default:
result = false;
}
return result;
};
$.fn.popoverTip = function ()
{
// jQuery
var tipId = '#' + this.attr('aria-describedby');
return $(tipId);
// Popover API by id
//var tipId = this.data('bs.popover').tip.id;
//return $(tipId);
// Popover API by object
//var tip = this.data('bs.popover').tip; // DOM element
//return $(tip);
};
// Load indicator
$.fn.loadIndicator = function (action)
{
var indicatorClass = 'loading';
// Take parent if no container has been defined
var $container = this.closest('.loading-container') || this.parent();
switch (action)
{
case 'show' :
$container.append($('<div>').addClass(indicatorClass));
break;
case 'hide' :
$container.find('.' + indicatorClass).remove();
break;
}
};
})(jQuery);
// Usage
// Assuming 'this' points to popover object (e.g. an anchor or a button)
// Check if popover tip is visible
var isVisible = $(this).isPopover('shown');
// Hide all popovers except this
if (!isVisible) $('[data-toggle="popover"]').not(this).popover('hide');
// Show load indicator inside tip on 'shown' event while loading an iframe content
$(this).on('shown.bs.popover', function ()
{
$(this).popoverTip().find('iframe').loadIndicator('show');
});
Here a way to check the state with Vanilla JS.
document.getElementById("popover-dashboard").nextElementSibling.classList.contains('popover');
This works with BS4:
$(document).on('show.bs.tooltip','#anElement', function() {
$('#anElement').data('isvisible', true);
});
$(document).on('hidden.bs.tooltip','#anElement', function() {
$('#anElement').data('isvisible', false);
});
if ($('#anElement').data('isvisible'))
{
// popover is visible
$('#tipUTAbiertas').tooltip('hide');
$('#tipUTAbiertas').tooltip('show');
}
Bootstrap 5:
const toggler = document.getElementById(togglerId);
const popover = bootstrap.Popover.getInstance(toggler);
const isShowing = popover && popover.tip && popover.tip.classList.contains('show');
Using a popover with boostrap 4, tip() doesn't seem to be a function anymore. This is one way to check if a popover is enabled, basically if it has been clicked and is active:
if ($('#element').data('bs.popover')._activeTrigger.click == true){
...do something
}
I know this should be simple, but it doesn't appear to be working the way I hoped it would.
I'm trying to dynamically generate jQuery UI dialogs for element "help."
I want to toggle the visibility of the dialog on close (x button in dialog), and clicking of the help icon. This way, a user should be able to bring up the dialog and get rid of it, as needed, multiple times during a page view.
// On creation of page, run the following to create dialogs for help
// (inside a function called from document.ready())
$("div.tooltip").each(function (index, Element) {
$(Element).dialog({
autoOpen: false,
title: $(Element).attr("title"),
dialogClass: 'tooltip-dialog'
});
});
$("a.help").live("click", function (event) {
var helpDiv = "div#" + $(this).closest("span.help").attr("id");
var dialogState = $(helpDiv).dialog("isOpen");
// If open, close. If closed, open.
dialogState ? $(helpDiv).dialog('close') : $(helpDiv).dialog('open');
});
Edit: Updated code to current version. Still having an issue with value of dialogState and dialog('open')/dialog('close').
I can get a true/false value from $(Element).dialog("isOpen") within the each. When I try to find the element later (using a slightly different selector), I appear to be unable to successfully call $(helpDiv).dialog("isOpen"). This returns [] instead of true/false. Any thoughts as to what I'm doing wrong? I've been at this for about a day and a half at this point...
Maybe replace the line declaring dialogState with var dialogState = ! $(helpDiv).dialog( "isOpen" );.
Explanation: $(helpDiv).dialog( "option", "hide" ) does not test if the dialog is open. It gets the type of effect that will be used when the dialog is closed. To test if the dialog is open, you should use $(helpDiv).dialog( "isOpen" ). For more details, see http://jqueryui.com/demos/dialog/#options and http://jqueryui.com/demos/dialog/#methods.
I was able to get it working using the following code:
$("div.tooltip").each(function (index, Element) {
var helpDivId = '#d' + $(Element).attr('id').substr(1);
var helpDiv = $(helpDivId).first();
$(Element).dialog({
autoOpen: true,
title: $(Element).attr("title"),
dialogClass: 'tooltip-dialog'
});
});
// Show or hide the help tooltip when the user clicks on the balloon
$("a.help").live("click", function (event) {
var helpDivId = '#d' + $(this).closest('span.help').attr('id').substr(1);
var helpDiv = $(helpDivId).first();
var dialogState = helpDiv.dialog('isOpen');
dialogState ? helpDiv.dialog('close') : helpDiv.dialog('open');
});
I changed the selectors so that they're identical, instead of just selecting the same element. I also broke out the Id, div and state into separate variables.
I have the following script in between the head tags on my page:
$.ajax({
type: "POST",
url: "my script that gets what I need",
context: document.body,
success: function(data){
//data is now the value that PHP echoed
phpsaid = data.split('|');
var size_ind = phpsaid.length/6;
var size_per = 6;
for (var i_one =0; i_one<size_ind; i_one++){
for(var i_two =0; i_two<1; i_two++){
if(i_one == 0 ){
var i_get = 0
}
else{
var i_get = i_one * 6;
}
$("#big_container").append("<div class ='neato'><div class ='c1'>"+phpsaid[i_get]+"</div><div class ='c2'>"+phpsaid[i_get+1]+"</div><div class ='c3'>"+phpsaid[i_get+2]+"</div><div class ='c4'>"+phpsaid[i_get+3]+"</div><div class ='c5'>"+phpsaid[i_get+4]+"</div></div>")
}
}
}
});
Then in the main body I have:
<div id ="big_container">
</div>
The ajax script above is generating the divs to go inside big_container. The client has specified that it be done strictly in that way (meaning generate all divs with ajax on the fly), so conceptual arguments of different ways to tackle it unfortunately won't help much here.
Here is my problem:
I also want to apply the following plugin to all elements of big_container. This of course works perfectly when I hard code the div elements into the page, but I cannot get it to work on the ajax generated divs within #big_container.
$(function(){
$('#big_container').bxSlider({
mode: 'vertical',
ticker: true,
tickerSpeed: 4500,
displaySlideQty: 5
});
});
How do I get the plugin function to apply to the ajax generated div's once they have in fact been generated?
Insert your initialization code after $("#big_container").append("...");
It will look like
$("#big_container").append("<div class ='neato'>..and so on..");
}
} // the end of the 'for' loops
$("#big_container").bxSlider({
mode: 'vertical',
ticker: true,
tickerSpeed: 4500,
displaySlideQty: 5
});
If you call ajax again on the page and add a new content to the existing one then it is better to write the call of the bxSlider as
$("#big_container .neato:last").bxSlider({
mode: 'vertical',
ticker: true,
tickerSpeed: 4500,
displaySlideQty: 5
});
just after .append part
This is a common problem people face that elements generated by ajax (dynamically inserted in to dom) doesn't take action or notified by any of the listener or any plugin inside ready because they are not registered in the ready event. To solve this kind of problem I use a different approach like the following
$(document).ready(function(){
myReadyFunction();
});
function myReadyFunction()
{
$("#big_container .neato:last").bxSlider({...});
// All other codes that normally reside inside ready event.
}
After each ajax call, upon success (if required) simply call myReadyFunction(); and in your case you can place your $("#big_container").bxSlider({...}) inside the myReadyFunction(); and call the myReadyFunction(); after successful ajax call and initially call myReadyFunction(); inside ready event too.