GemcodeDM GemcodeDM - 1 month ago 20
HTML Question

jQuery mouseenter and mouseleave creates flickering

First of all I would like to say this isnt a repeat question as I have taken a look at the other questions and nothing seems to work/is applicable for what I am doing.

the problem is when i hover my mouse over the target div the effect flickers if i move my mouse, it does not flicker if i hover over the div and keep my mouse in the same place.

I have tried use .show and .hide instead and other functions that would give me the desired effect but i still get the flickering issue.

This is the HTML i used.

<div class="four-icons">
<div class="icon-wrapper col-md-3">
<div class="mouse-over-1"><img src="img/bookatable-hover.png"></div>
<img class="icons-1" src="img/book%20a%20table.jpg">
</div>
<div class="icon-wrapper col-md-3">
<div class="mouse-over-2"><img src="img/menus-hover.png"></div>
<img class="icons-2" src="img/menus.jpg">
</div>
<div class="icon-wrapper col-md-3">
<div class="mouse-over-3"><img src="img/christmas-hover.png"></div>
<img class="icons-3" src="img/christmas.jpg">
</div>
<div class="icon-wrapper col-md-3">
<div class="mouse-over-4"><img src="img/contactus-hover.png"></div>
<img class="icons-4" src="img/contact.jpg">
</div>
</div>


this is the corresponding jQuery:

$(document).ready(function(){


$("img.icons-1").mouseenter(function(){
$("div.mouse-over-1").css("display", "block").css("position", "absolute");
});
$("img.icons-1").mouseleave(function(){
$("div.mouse-over-1").css("display", "none");
});



$("img.icons-2").mouseover(function(){
$("div.mouse-over-2").css("display", "block").css("position", "absolute");
});
$("img.icons-2").mouseout(function(){
$("div.mouse-over-2").css("display", "none");
});



$("img.icons-3").mouseover(function(){
$("div.mouse-over-3").css("display", "block").css("position", "absolute");
});
$("img.icons-3").mouseout(function(){
$("div.mouse-over-3").css("display", "none");
});



$("img.icons-4").mouseover(function(){
$("div.mouse-over-4").css("display", "block").css("position", "absolute");
});
$("img.icons-4").mouseout(function(){
$("div.mouse-over-4").css("display", "none");
});


});


here is where the code lives: http://muhammadkasimali.co.uk/Cruise/
just in case you would like to replicate the issue.

Also, i did try to create a JSfiddle but could not get it to work, i am pretty much a noob so I am sorry if this is a bad question.

Answer

You should bind the mouseenter/mouseleave event on the parent element, this code should work:

Javascript

$(document).ready(function(){

    $(".icon-wrapper").mouseenter(function(){
        $(this).find('div').css("display", "block").css("position", "absolute");
    });
    $(".icon-wrapper").mouseleave(function(){
        $(this).find('div').css("display", "none");
    });

});