Skip to content Skip to sidebar Skip to footer

Jquery Mouseover Event Not Working Right?

I have this code: $('document').ready( function () { $('.userPic').mouseover(function () { $('.changePic img').css('display', 'block'); }) $('.userPic').mouseou

Solution 1:

If you don't need to support IE6, you can do this without JavaScript (see below). First, though, the JavaScript + jQuery answer:

Using jQuery

You want to use mouseenter and mouseleave instead of mouseover and mouseout. mouseover and mouseoutbubble, so when they fire on elements within the element you're watching, you receive them at the element you're watching. It can get complicated quickly. mouseenter and mouseleaveonly happen when the mouse enters or leaves the specific element in question (they don't bubble). Originally they were IE-specific events, but jQuery emulates them on browsers that don't support them natively.

Separately, are you sure you really want to operate on all of the img elements in all of the elements with the "changePic" class? Or only the ones within the specific element your mouse is over? If the latter, you also want to update your code to use find, like so:

jQuery(function($) {

  $(".userPic").mouseover(function () {
    $(this).find(".changePic img").css("display", "block");
  });

  $(".userPic").mouseout(function () {
    $(this).find(".changePic img").css("display", "none");
  });

});

Live example

Using CSS

But note that you can do this with CSS unless you need to support IE6. Just use style rules:

.userPic.changePicimg {
    display: none;
}
.userPic:hover.changePicimg {
    display: inline;
}

Live example

No JavaScript required. But the hover pseudo-class doesn't work in IE6 except on a elements. (Be sure to remove the inline style="display: none" that I assume you currently have on the images.)

Post a Comment for "Jquery Mouseover Event Not Working Right?"