Fistright Fistright - 6 months ago 9
Javascript Question

Bug in Function to detect mouse direction

i have written a function to detect mouse direction and it works but it has a bug.When i put mouse's pointer from left into the div for the first time the function calculate that mouse's pointer has moved to right direction when it is called for the first time,then it works well.I don't know if i explained wll my issue but you can easily see the bug in your browser's console seeing at the first printed values.

This is my code

<body>
<div id="padre-relative">

</div>
</body>



#padre-relative{
position:relative;
width:300px;
height:300px;
overflow: hidden;
background: red;
margin-left:300px;

}





window.onload=function(){

var storageMousePositionX=0;

var positionMouseX=0;


document.getElementById("padre-relative").onmousemove= function(){


positionMouseX=event.clientX;

if(positionMouseX > storageMousePositionX){

console.log("right");

}
if(positionMouseX < storageMousePositionX){
console.log("left");

}
storageMousePositionX=positionMouseX;

};

};

Answer

This is beacause you set your var storageMousePositionX to 0 on load. You should set it for the first time when you enter the div.

document.getElementById("padre-relative").onmouseenter = function(){
  storageMousePositionX = event.clientX;
}

See this fiddle