I am implementing my own ‘tooltip’ where it creates a new div element every time you hover over it and removes it on hover out. The code below is stripped down from what I use but it shows the problem: This piece of code works perfect when a user slowly puts their mouse over and off the $(‘#’ + fieldName) object but when you move your mouse on the object and then quickly pull it off the tooltip does not get removed. Is there a way to improve my code?
I tried implementing a system where I create all the tooltip boxes and hide them, then show them on hover, but it posed the same problem with the mouse moving quickly off the object and the hover out not firing.
$('#' + fieldName).hover(
function () { /* Create new DOM element */
/* My ajax stuff here */
var data = 'test';
var tooltipBox = $('<div id="' + fieldName + '_tooltip">' + data + '</div>');
$("body").prepend(tooltipBox);
},
function () { /* Remove Tooltip from DOM */
$('#' + fieldName + '_tooltip').remove();
}
);
Answer:
With help from Robert Koritnik and sajawikio:
If you need to make tooltips on hover with AJAX calls in the hover you can do a small hack to make it work.
var callingAjax = false;
var removeTooltip = false;
$('#tooltip').hover(
function() {
callingAjax = true;
$.post(.. {
callingAjax = false;
/* do stuff */
if(removeTooltip)
/* code to remove tooltip */
removeTooltip = false;
});
},
function() {
if(callingAjax)
removeTooltip = true;
else
/* code to remove tooltip */
}
);
Your code works
I’ve put your code in a JSFiddle and it works, so you must have some other problem. I can move mouse as fast over the link as possible but tooltip gets removed every single time.
I’m using Chrome. What’s your drug?
The actual problem
The problem is that you’re executing other things in hover before creating tooltip. It doesn’t really matter whether that’s an Ajax call. It may be anything that is asynchronous so Javascript thread can execute next functions. And if that executes longer than you stay on the element, your mouse out want’s to remove something that hasn’t been created yet (and will be later on).
Two possible solutions:
Warning
I would strongly suggest to not execute ajax code in hover event because you may fire lots and lots requests. Actually, more than browser can handle. If you must execute ajax request on hover then do it this way: hover fires and prepares a function call to be executed right after it, but that function will only issue an Ajax call if one is not being in progress already: