HTML Dog

Skip to navigation

Suckerfish :focus

By Patrick Griffiths and Dan Webb.

The :focus pseudo-class can be used to apply styles to a page element that receives focus. So, for example, if you wanted the background colour of input boxes to change when they are in use by the user, you can simply do:


input:focus { background: orange; }

IE doesn't recognise this at all, so with a quick shake of the Suckerfishes tail:


sfFocus = function() {
	var sfEls = document.getElementsByTagName("INPUT");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onfocus=function() {
			this.className+=" sffocus";
		}
		sfEls[i].onblur=function() {
			this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfFocus);

This applies the Suckerfish to allinput elements, so with a minor addition to the CSS:


input:focus, input.sffocus { background: orange; }

All works well in Focusland.

If you wanted to apply this to more than one element, such as input and textarea, you can use a variant of the Suckerfish Shoal, which not only makes it easy to use more than one Suckerfish function at a time, it also makes it easy to apply any given function to more than one element.

Examples

As already mentioned, you can use this method to highlight form elements (which HTML Dog also employs) or you could use it to aid accessibility for people who don't use pointing devices and tab through links, by highlighting the link in focus.