Wednesday, April 10, 2013

JQuery - Imitating a "pause \ resume" with ".animate"

I spent some time working on a project to use the core ".animate" method provided in JQuery and became quickly astounded that it included only a measure for halting the animation(".stop()" or "clearQueue()"), but not resuming. Google showed me a few additional plugins to add this functionality, but I wasn't in the mood to mix libraries to accomplish this goal. A bit of trial, error, and clever use of style properties landed me with victory. I used the stop function to halt at the event handler onmouseover, then passed the current margin to lock in the new starting margin style property, then re-initiated the original animation via onmouseout to carry to the previously coded margin. Presto!

*NOTE - this is based on 1.8.2/jquery.min.js"

 <script type="text/javascript">
function startSpotLight()
{
$("#AnimateMe").animate({
     "margin-top" : "-725px"}, 20000, 'linear');
}

function stopSpotLight()
{
var myDiv = $("#AnimateMe");
myDiv.clearQueue();
myDiv.stop();
}

function setSpotLightStream(pause)
{
document.getElementById('AnimateMe').style.marginTop=pause;
startSpotLight();

}
</script>


HTML Later on...

<div id="AnimateMe" onmouseover="javascript: stopSpotLight();" onmouseout="javascript: setSpotLightStream(document.getElementById(this.id).style.marginTop);startSpotLight();">

<!--IMAGES-->

</div>