views:

41

answers:

1

Hi,

I'm developing a web site which shows different images in a loop using cross fading. Now, I want this loop to start no earlier than the page is actually shown by the user. The typical scenario is when the user fires up a new tab entering the url of my site, goes back to an old tab (or opens a new tab), waiting for my site to load. As soon as the site has been loaded, he goes back to the tab where my site has been loaded: I want the loop to start only when the tab containing the loaded page gets the focus.

How can I do that? I'm using the jQuery lib but plain vanilla javascript would be as great.

Thanks.

+1  A: 
<html><head>

<script type="text/javascript">
window.__hasfocus = true;
window.onload = function() {
    window.__loaded = true;
    if(window.__hasfocus && !window.__startFlag) start();
}
window.onblur = function() { window.__hasfocus = false; }
window.onfocus = function() {
    if(window.__loaded && !window.__startFlag) start();
}
function start() {
    window.__startFlag = true;
    alert('starting');
}
</script>
</head>

<body>
<img title="" src="http://stereo.gsfc.nasa.gov/img/spaceweather/preview/tricompSW.jpg"&gt;
</body>
</html>
Rob
as a general rule, don't do `window.onload=...`, etc. as it will override other handlers. it's a bad habit that can lead to problems with complex pages. use jQuery's event binding to take care of this, since it is available and easy.
geowa4
still +1 for the right idea though.
geowa4
Right, I'm not familiar with jquery but in mootools you can dowindow.addEvent('load') = function() { ... }I'm guessing it's similar in jquery.
Rob

related questions