I have a neat little jQuery script I am working on.
Goal: parent div with overflow hidden holds a larger div with image. When I move the mouse to the left or right of the parent div, the div with image changes margin-left to move left or right.
Problem is… if I move the mouse out of the parent div (left or right), the image keeps going. I need the image to stop when the mouse is not on the inside left or right edge of the parent div.
Any ideas?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
//<![CDATA[
jQuery.noConflict ();
jQuery(document).ready(function(){
jQuery('#container').mousemove(function(e){
var parentWidth = jQuery('#container').width();
var parentWidthLeft = Math.round(.1 * jQuery('#container').width());
var parentWidthRight = Math.round(jQuery('#container').width() - parentWidthLeft);
var parentHeight = jQuery('#container').height();
var parentOffset = jQuery('#container').offset();
var X = Math.round(e.pageX - parentOffset.left);
var Y = Math.round(e.pageY - parentOffset.top);
if (X<parentWidthLeft)
{
jQuery('#image').animate({'left': '-' + parentWidth }, 5000);
}
if (X>parentWidthRight)
{
jQuery('#image').animate({'left': parentWidth }, 5000);
}
if (X<=parentWidthRight && X>=parentWidthLeft)
{
jQuery('#image').stop();
}
if (X<1)
{
jQuery('#image').stop();
}
});
jQuery('#container').mouseleave(function(){
jQuery('#image').stop();
});
});
// ]]>
</script>
</head>
<body>
<div id="container" style="width: 500px; height: 500px; overflow: hidden; border: 10px solid #000; position: relative; margin: auto auto;">
<div id="image" style="position: absolute; left: 0; top: 0;"><img src="http://dump4free.com/imgdump/1/Carmen-Electra_1wallpaper1024x768.jpg" alt="" /></div>
</div>
</body>
</html>
The stop() function of jQuery can have a boolean parameter named “clearQueue”.
If you try to use .stop(true) instead of .stop(), the animation will stop correctly, and your page run well.
The fact is when you move your mouse, a lot of event are fired and a lot of animation are triggered.
One is currently running, and all others are store in a queue, and executed later (after the first animation finish).
In this way, the framework has a “memory” of the chronological list of event.
By using stop(true), you order to flush completely the queue of animation.