window onload and window onfocus

Henrikh picture Henrikh · Jun 19, 2011 · Viewed 29.2k times · Source
window.onload = function() {
window.onfocus = alert('example');
}

I've met this problem, anyone can help? I'm new at javascript and made this expecting to work properly, but it does not :)

I want to alert the word "example" when the page is fully loaded and active, but don't want to alert the word "example" if the page is fully loaded but not active (onblur). And when user comes back (onfocus) then alert "example".

Answer

SLaks picture SLaks · Jun 19, 2011

Your code calls the alert function immediately and assigns its return value to onfocus.

You need to set onfocus to an anonymous function that calls alert:

window.onload = function() { 
    window.onfocus = function() { alert('example'); };
};