Peeja
Peeja

Reputation: 14264

How can I detect whether a browser window is focused or not?

My page should make notification sounds only when the window is in the background. I can track the window.onfocus and window.onblur events to notice when the focus state changes. However, I don't know whether the window will load focused or not, since it might load in a background tab, for instance.

How do I decide whether to play sounds or not before I get an onfocus/onblur event?

Upvotes: 7

Views: 6472

Answers (2)

Patrick McElhaney
Patrick McElhaney

Reputation: 59271

The onfocus event should be triggered when the page is initially opened (in the foreground). At least it is in FF3/IE8.

So you could have sounds on initially, turn them off when onfocus is triggered, and turn them back on when onblur is triggered.

Upvotes: 0

Jed Schmidt
Jed Schmidt

Reputation: 2955

Couldn't you just assume it's loaded blurred, and then change the status to focused as soon as you receive any type of event (keydown/mousemove)?

Upvotes: 2

Related Questions