Skip to content Skip to sidebar Skip to footer

Javascript Mouseover/mouseout Issue With Child Element

I have this little problem and I am requesting for your help. I have a div element, inside which I have an img element, like this

Solution 1:

you can use "mouseenter" and "mouseleave" events available in jquery, here is the below code,

$(document).ready(function () {
        $("#parent").mouseenter(function () {
            $("#child").show();
        });
        $("#parent").mouseleave(function () {
            $("#child").hide();
        });
    });

above is to attach an event,

<div id="parent">
    <img id="child" src="button.png" style="display:none;" />
</div>

Solution 2:

You can use the solution below, which it's pure javascript and I used with success.

var container = document.getElementById("container");
var mouse = {x: 0, y: 0};

functionmouseTracking(e) {
    mouse.x = e.clientX || e.pageX;
    mouse.y = e.clientY || e.pageY;
    var containerRectangle = container.getBoundingClientRect();

    if (mouse.x > containerRectangle.left && mouse.x < containerRectangle.right &&
            mouse.y > containerRectangle.top && mouse.y < containerRectangle.bottom) {
        // Mouse is inside container.
    } else {
        // Mouse is outside container.
    }
}
document.onmousemove = function () {
    if (document.addEventListener) {
        document.addEventListener('mousemove', function (e) {
            mouseTracking(e);
        }, false);
    } elseif (document.attachEvent) {
        // For IE8 and earlier versions.mouseTracking(window.event);
    }
}

I hope it helps.

Solution 3:

Just add an if statement to your MyFuncOut function which checks the target is not the image

if (event.target !== imageNode) {
     imageNode.style.display = 'none'
}

Solution 4:

I've had problems with this too and couldn't get it to work. This is what I did instead. It's much easier and isn't JavaScript so it's faster and can't be turned off.

div.container {
    opacity:0.0;
    filter:alpha(opacity="00");
}

div.container:hover {
    opacity:1.0;
    filter:alpha(opacity="100");
}

You can even add the CSS3 transition for opacity to give it a smoother feel to it.

Solution 5:

Simply set css of the child element pointer-event:none; See example:

#parent {
  width: 500px;
  height: 500px;
  border: 1px solid black;
}

#child {
  width: 200px;
  pointer-events: none; # this does the trick
}
<divid="parent"onmouseover="MyFuncHover()"onmouseout="MyFuncOut()"><imgid="child"src="https://i2.wp.com/beebom.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg?w=640&ssl=1" /></div><scripttype="text/javascript">functionMyFuncHover() {
      console.log("mouse over")
    }

    functionMyFuncOut() {
      console.log("mouse out")
    }
</script>

Post a Comment for "Javascript Mouseover/mouseout Issue With Child Element"