Implement setFocus() on Elements with MooTools

By  on  

Every DOM node provides a focus method but most nodes have a tabIndex of -1 which prevents the element from being focused on when clicked, tabbed, focused via JavaScript.  I've been tinkering around with ways to make focusing on any element effortless with varying results.  I tried monkey-patching the prototype which worked well in Safari and Chrome but nowhere else.  I tried doing a tabIndex check but IE complained.  In the end I came up with more of a shortcut method than anything else.

The MooTools JavaScript

This method can be used by any node but it could cause issues with resetting an explicitly set tabIndex.

	setFocus: function(index) {
		this.setAttribute('tabIndex',index || 0);

Using this method is simple:


There you have it.  Depending on the node, the element may have a dotted outline as you would expect.  Otherwise you can add onFocus and onBlur events to your DIVs, SPANs, and other nodes.

Recent Features

Incredible Demos

  • By
    MooTools Zoomer Plugin

    I love to look around the MooTools Forge. As someone that creates lots of plugins, I get a lot of joy out of seeing what other developers are creating and possibly even how I could improve them. One great plugin I've found is...

  • By
    MooTools Fun with Fx.Shake

    Adding movement to your website is a great way to attract attention to specific elements that you want users to notice. Of course you could use Flash or an animated GIF to achieve the movement effect but graphics can be difficult to maintain. Enter...


  1. Eric C.

    Simple, yet effective, I like it!

  2. Very cool! I was just asking myself how elements are focused in JS while working on my ARAI Class.

    I think this should be part of more. It’s simple and can be very useful for many scenarios.

  3. What does this part means?

    ...abIndex',index || 0);

    What is the “index” there means?

  4. Erenss

    Hi every body, nice technic but in my case Firefox send back : ReferenceError: setFocus is not defined
    while in chrome work fine!

  5. Thanks worked for me..

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!