Is there a way to start a timer in my flash MovieClip when it is currently visible in the viewport of a HTML page without using Javascript + ExternalInterface? Maybe an event or another trick?
I'd like to start/stop a timer when this happens.
Is there a way to start a timer in my flash MovieClip when it is currently visible in the viewport of a HTML page without using Javascript + ExternalInterface? Maybe an event or another trick?
I'd like to start/stop a timer when this happens.
Like you already discovered the ThrottleEvent
will tell you when the Flash Player has been throttled in cases where that is supported, which includes scrolling off screen and browser tab switching.
In addition to that, you can manually detect if the Flash object is visible using JavaScript and callbacks in Flash. Example:
First, set up callbacks in your SWF to pause and resume your timer:
var timer:Timer = new Timer(1000);
ExternalInterface.addCallback("pause", timer.pause);
ExternalInterface.addCallback("resume", timer.resume);
Next, in your HTML, track the position of your Flash object within the HTML viewport, and call into the SWF when a change occurs. Here's a good example of doing this: How to tell if a DOM element is visible in the current viewport?
You handler would simply need to track when the Flash object visibility changes and call into the SWF when it does:
function isElementInViewport (element) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
$(window).on('DOMContentLoaded load resize scroll', handler);
var flashIsVisible = false;
function handler(e){
var flash = document.getElementById("myFlash");
var isVisible = isElementInViewport(flash);
if(isVisible != flashIsVisible){
flashIsVisible = isVisible;
isVisible ? flash.resume() : flash.pause();
}
}
You can try with Event.ACTIVATE
or Event.DEACTIVATE
, but what that does is just triggers event when your flash file gain or lose focus. Maybe that is your answer.