Stop an Animation/Video From Playing When Hiding the Object

By default in HTML, if a Flash object is hidden, the DOM will not play nor load the animation. However, what happens if you have some tabs that hide the animation or video? This was an issue I ran into when building my portfolio. After doing some digging I found a solid solution that worked well for stopping the animation or video.

Discovering the Problem

In my portfolio, I have all my animations on the page at once, but are all hidden by default showing only a static image thumbnail. The DOM will not play Flash animations automatically by default, so it worked fine during the early testing of the site. However, I ran into a Firefox update that changed how the Flash played when hiding the parent div of the Flash object. It used to be that Firefox would stop playing the Flash when it was hidden but the update changed it to where it kept playing in the background. Upon further research I found that other browsers were doing the same thing. It was never a problem on the initial load of the page because the CSS hid the objects; it was only when I went to hide the animation and continue to play that it became a problem. This was also happening on any video content as all my SWF’s have alternative video (hosted on Vimeo) counterparts if the Flash player is not available.

Finding a solution

I could have added a stop/play button to all my animations, but that was not the intent of the original design, plus this put an extra burden on reprogramming them; it would also add an additional click to stop the animation before hiding/closing the parent div. As for the video, I thought I could control it using a Vimeo API, froogaloop, when I closed the parent div, worked OK but proved troublesome in some cases.

I finally came across a solution that ended up being much simpler than I thought it would be by using only a few lines of jQuery. It consists of cloning the object, hiding the parent div, placing the clone where the original resides, and deleting the original object. Since the DOM will not play a hidden object and the newly cloned object is fresh and hasn’t played yet, the new cloned object will not play and will replay from the beginning when shown again.

Here is the jQuery code snippet:

// detail is the parent div where the active animation resides
$j(detail).children('.close') // the close button
	  .click(function(){
		showThumbs(); // show thumbnails and other actions
		var _clone = $j(detail).clone(true);
		var _par = $j(detail).parent();
		$j(detail).remove(); // remove original to stop all play in DOM
		$j(_clone).hide() // hide the clone
			  .removeClass("active");
		_par.append(_clone); // append to where the original resided
	});
}

Conclusion

Sometimes a seemingly difficult problem requires only the easiest solution. The clone() method is now my friend and I continue to use it more frequently. I hope you too find it useful.