简体   繁体   中英

Jquery .hover - flickering image

I have a .hover() function setup in jQuery for the following test page:

As you will see the overlay I want to appear when hovering over the product image flickers as you move your mouse over it. Any ideas as to why, and what I can do to fix it? Does it have something to do with the jQuery cycle plugin I have applied to the images?

$("#productImage_1").hover(
    function() {
        $('#product_1').show();
    },
    function() {
        $('#product_1').hide();
    }
);

The problem is most likley that once the overlay appears, you are no longer hovering #productImage_1 . You are now hovering #product_1 . This creates an infinite loop of appearing and disappearing (the flickering).

$("#productImage_1, #product_1").hover(function() {
    $('#product_1').show();
}, function() {
    $('#product_1').hide();
});

The problem occurs because .productOverlay is being shown ontop of #product_1, therefore the mouseleave event is triggered, and thus, it is being hidden again.

There are many ways of dealing with this, but one of the smoothest solutions (that will require least amount of event listeners) is to check the e.target element, and see if it's the overlay. As such:

$("#productImage_1").hover(function(e) {
    $('#product_1').show();
}, function(e) {
    // Prevent execution if it's the overlay that is being targeted
    if (e.target.className == 'productOverlay')
        return;

    // Otherwise, hide!
    $('#product_1').hide();
});

EDIT: I encourage people to use as much vanilla JS as possible; therefore the use of className instead of doing something like $(e.target).hasClass() . Why? Performance! Later on as your application grows bigger, you will have to pay attention to events and how they perform; especially on mouse-related events. You want to avoid long-running code in events, therefore go by the native solution :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM