Thanks for your help on my last noobie jquery question and since you done good, I have another for you :) The script below allows me to perform some simple AJAX by retrieving some static markup from another HTML file and insert it into my homepage. I'm experiencing a bug that I think is related to the magic of asynchronicity, but since I'm new to AJAX, I'm not sure.
When I move my mouse over a link, it retrieves the HTML and inserts it into my homepage. When I move my mouse off the link, it should remove the new HTML that was inserted. The bug presents itself when sometimes the HTML is inserted, but not removed when you move the mouse on/off the link very quickly. My theory is the "mouse off" function is called before the HTML is actually inserted, do you agree? If so, any thoughts on how to fix this? Here's the script...
$(function()
{
//HOVER EFFECT FOR CONTACT LINK
$('a#contact_link').hover(function()
{
$('<div id="contact_container" />').load('contact.htm #contact', function()
{
$(this).stop()
.hide()
.insertAfter('#header')
.slideDown(250);
});
},
//MOUSE OFF EFFECT FOR CONTACT LINK
function()
{
$('#contact_container').remove();
});
});
Thanks so much in advance for all your help!
EDIT* Thanks to your replies, I changed my script and the bug seems to be fixed...
$(function()
{
//RETRIEVE THE MARKUP AT PAGE LOAD
$('<div id="contact_container" />').load('contact.htm #contact', function()
{
$(this).hide()
.insertAfter('#header');
});
//HOVER EFFECT FOR CONTACT LINK, SHOW THE MARKUP
$('a#contact_link').hover(function()
{
$('#contact_container').stop()
.slideDown(250);
},
//MOUSE OFF EFFECT FOR CONTACT LINK, HIDE THE MARKUP
function()
{
$('#contact_container').stop()
.hide();
});
});
I can still see potential for a few bugs in this script, but i'll save that for another question ;) thanks everyone!
Why don't you fill the content only one time and hide the div when mouse is out. When again hover is invoked if the div is present in the DOM just change the visibility of the div.
Each time loading the div with an Ajax response won't be a good idea if the resulting response is the same.