Reputation: 3720
In my code, hovering over an image creates a new link with a class of '.pin_it' on top of that image. If the user moves the mouse away from the image, the .pin_it should hide. However, if they move the mouse over the new .pin_it, it should stay visible.
I've got this all working. The problem is that after they have moused over .pin_it, moving outside the image should hide .pin_it, but it doesn't. Then, if you hover back in, it will add ANOTHER .pin_it, but will not respect the mouse-out behavior at all any more.
What am I doing wrong?
JS Fiddle -> http://jsfiddle.net/kthornbloom/rKZK5/2/
Code:
$('img').hover(
function() {
var imgWidth = $(this).width();
var imgPosition = $(this).offset();
if(imgWidth > 300) {
$('body').append('<a href="#" class="pin_it">Pin It</a>');
$('.pin_it').css(imgPosition);
}
else {
// Do Nothing
}
}, function() {
var isHovered = $('.pin_it').is(":hover");
if (isHovered == true) {
//Do nothing
} else {
$('.pin_it').remove();
}
});
Upvotes: 1
Views: 83
Reputation: 30993
You can reconsider your markup, by:
Code:
$('#imgWrapper').hover(
function () {
var imgWidth = $(this).width();
var imgPosition = $(this).offset();
if (imgWidth > 300) {
$('.pin_it').css(imgPosition).show();
} else {
//
}
}, function () {
$('.pin_it').hide();
});
You'll have no problems with heavy DOM manipulation from add/remove elements and the code looks simple.
Demo: http://jsfiddle.net/IrvinDominin/fzM7k/
Upvotes: 2