Search code examples
javascriptjquerymouseoverjquery-hovermouseenter

Hover(), mouseenter(), mouseover(), etc jumping back and forth


I am trying to make a situation when you hover over an image then it will hide an image and show another. and the other way around when you hover out.

I have tried using all the various hover effects that comes to mind like mouseenter, mouseover, hover, etc.

They all cause the same problem. If i very firmly and quickly drag my cursor into the field of action then it will give me the desired effect. however if i slowly drag my cursor into the field of action then it will jump between the images a couple of times before finally stopping at the correct image.

this looks very unprofessional and i want it to be much more consequent doing this action so that no matter if i do it slow or fast then it will only jump once.

this is my script:

$("#DenmarkMap").hide();
$("#InfoBadge1").hover(function(){
    $("#InfoLogo").hide("puff");
    $("#DenmarkMap").show("puff");
}, function(){
    $("#DenmarkMap").hide("puff");
    $("#InfoLogo").show("puff");
});

this is a non working fiddle https://jsfiddle.net/ydeLvxx2/

hope you guys can help me figure this out.


Solution

  • Here is a pure Javascript solution (no jQuery needed)

    https://jsfiddle.net/uL0hpxbu/ Update: version with CSS3 "puff" effect: https://jsfiddle.net/230ta4tk/2/

    Here is how the main script looks like:

        var InfoBadge1 = document.getElementById("InfoBadge1");
        var InfoLogo = document.getElementById("InfoLogo");
        var DenmarkMap = document.getElementById("DenmarkMap");
    
        InfoBadge1.addEventListener("mouseover", function() {
          InfoLogo.classList.toggle("puff");
          DenmarkMap.classList.toggle("puff");
        });
        InfoBadge1.addEventListener("mouseout", function() {
          InfoLogo.classList.toggle("puff");
          DenmarkMap.classList.toggle("puff");
        });
    

    and CSS part (just an example, change it as you want)

        #DenmarkMap {
          position: absolute;
          left: 0;
          top: 0;
          transition: .5s all;
        }
        #InfoLogo {
          position: absolute;
          left: 250px;
          top: 120px;
          transition: .5s all;
        }
        #InfoBadge1 {
            position: absolute;
            left: 0px;
            top: 120px;
        }
        .puff {
          transform: scale(1.2);
          opacity: 0;
        }
    

    and HTML:

    <img id="InfoBadge1" src="http://dummyimage.com/200x100/803580/ffffff&text=InfoBadge1" alt="" />
    <img id="InfoLogo" src="http://dummyimage.com/200x100/803580/ffffff&text=InfoLogo" alt="" />
    <img id="DenmarkMap" class="puff" src="http://dummyimage.com/200x100/3c8036/ffffff&text=DenmarkMap" alt="" />