I wrote a program to animate a div content. This is working according to the mouse position. On mousemove event, if mouse position is more than 1/3 of window height content will animate to up (content will appears). Otherwise it will animate to downside (disappears). The program is giving proper result but it is taking time. I think the animate function is calling multiple times.
How can I improve the code?
Please check the code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var ww;
var wh;
var moverHeight="150";
var moveRespondPosition;
$(document).ready(function()
{
ww=$(window).width();
wh=$(window).height();
$("#mover")
.css("height",moverHeight)
.css("bottom",-moverHeight);
moveRespondPosition=wh-(wh/3);
$(document).mousemove(function(e)
{
var mousePosition=e.pageY;
if(mousePosition>moveRespondPosition)
{
setTimeout('animateElem(0)',100);
}
else
{
setTimeout('animateElem(-moverHeight)',100);
}
});
});
function animateElem(value)
{
$("#mover").animate
({
"bottom":value
});
}
</script>
<style type="text/css">
*
{
padding: 0px;
margin: 0px;
}
body
{
overflow-y: hidden;
}
#wraper
{
width: 100%;
height: 100%;
position: relative;
}
#mover
{
width: 100%;
background-color: #192B44;
position: absolute;
}
</style>
</head>
<body>
<div id="wraper">
<div id="mover">
Content
</div>
</div>
</body>
</html>
The problem is this part:
Basically, you are getting an event on each pixel move of the mouse and creating a new timer. So if the mouse is moved 100 pixels across the screen, you are creating 100 new timers, 1000 pixels and you get 1000 timers.
I’m not sure you even need to use setTimeout at all here, if you want a little delay you can do that with the animate call. But you’ll still have a problem with kicking off a jQuery animation on every pixel move. You should add a check so that you are only doing the animation when it’s needed.
Something like this might work better:
I would also recommend looking at http://benalman.com/projects/jquery-throttle-debounce-plugin/ to debounce your events. There is no need to be doing the calculation on every single pixel movement, if you just check once every 25ms it would look the same to the user but be much more performant.
If you include the debounce script from the link, you can use it like: