Wednesday, October 22nd, 2008

Fixing Loss of Focus on IE

Category: IE, JavaScript

Continuing with SitePen stories for today, Dustin Machi posted a short but interesting piece on how to detect loss of focus on IE6.

So your cool new app is perfect, but you want it to lock the user out when the browser hasn’t had focus after 15 minutes? Well that’s easy you think, I’ll just connect to the document’s blur and focus events and be good to go. You quickly add a little bit of code to your Dojo widget:

javascript

  1. dojo.connect(dojo.doc, "onblur", this, "onWindowBlur");
  2. dojo.connect(dojo.doc, "onfocus", this, "onWindowFocus");

After reluctantly firing up your Virtual Machine to test Internet Explorer 6, much to your dismay, onfocus events are immediately followed by onfocusout events. You feel the harsh reality that IE6 is going to suck away a bit more of your life.

Fortunately, while the solution seems to be difficult to track down on the “interwebs”, it is in fact pretty simple. The key is to understand that IE tracks the activeElement (document.activeElement) and fires onfocus and onfocusout events as the activeElement changes. As the onfocusout events occur, you must track what the activeElement is. When an onfocusout event happens and the activeElement doesn’t change, then the window has lost focus.

Here’s the final cross-browser version:

javascript

  1. if (dojo.isIE) {
  2.    dojo.connect(dojo.global, "onfocus", this, "onWindowFocus");
  3.         dojo.connect(dojo.doc, "onfocusout", this, function() {
  4.              if (this._activeElement != document.activeElement){
  5.                     this._activeElement = document.activeElement;
  6.              }else{
  7.                     this.onWindowBlur()
  8.              }
  9.         });
  10.  }else{
  11.     dojo.connect(dojo.doc, "onblur", this, "onWindowBlur");
  12.     dojo.connect(dojo.doc, "onfocus", this, "onWindowFocus");
  13.  }

Posted by Ben Galbraith at 8:00 am
2 Comments

+++--
3.5 rating from 26 votes

2 Comments »

Comments feed TrackBack URI

Great fix! Stuff like this is still helping people — lots of us still have to support IE6. (For instance, I’ll be _officially_ supporting IE6 for another few years, at least. :D Yay! )

Comment by mdmadph — October 22, 2008

Why Event Handler is a string in Dojo?
Why not just a funciton without ‘()’?

Comment by KKFC — October 22, 2008

Leave a comment

You must be logged in to post a comment.