I’m trying to make it so that a div will scroll when the mouse hovers over the an image but can only scroll so far. Somewhere its just not quite working
$(document).ready(function()
{
$('#test').bind('mouseenter', function()
{
var self = $(this);
var right = parseInt(self.style.left) || 200;
this.iid = setInterval(function()
{
if (right <= 400)
{
right += 200;
}
else
{
right = 400;
}
self.style.left = right + "px";
}, 525);
}).bind('mouseleave', function()
{
this.iid && clearInterval(this.iid);
});
});
#test {
color:white;
width: 400px;
height: 400px;
left: 200px;
background-color: #000;
position: absolute;
}
<div id="test">hover me please</div>
or a fiddle here:
http://jsfiddle.net/qjxqC/1/
Thanks for you help
First of all don’t attach a JavaScript property (iid) to a DOM reference (this) this.iid. This will cause memory leaks in certain browsers (IE). I’d also recommend a recursive timeout as well.
I’d use setTimeout for this operation. It provides more control given your limit check and easier break from within your function. Here is your code reworked.