Control window focus

Use the focus() method to control your window focus. Here's how.

By Brent Lee Metcalfe

A window that can't focus is like a plane that can't fly: it contains some pretty interesting stuff, but it can't ascend to the heights that it was built for. I've discussed focusing idiosyncrasies, so let's demo a focusing technique that's compatible across browsers.

When the onClick event handler fires the window titled "focus two!" (spawn) focuses its parent window "focus one!" (the opener) by first detecting whether it's blurred:

function onTop() {
  if (opener.blur) opener.focus();

If so, the parent window is brought to the top using the focus() method. Similarly, the parent window detects whether its child (the spawn) is blurred. If so, "focus two!" is placed on top:

function onTop() {
  if (spawn.blur) spawn.focus();

I haven't mentioned any "If nots" in the above because closing one window will close them both.

Brent Lee Metcalfe is a Web architecture consultant.

Editor's Picks

Free Newsletters, In your Inbox