kthornbloom
kthornbloom

Reputation: 3720

jQuery- Exclude from hover out

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

Answers (1)

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can reconsider your markup, by:

  • adding a wrapper for your image and inserting your pin button inside it and setting it not visible
  • when you hover the wrapper show the button
  • when you leave the wrapper hide the button

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

Related Questions