Wanted – onfocus/onblur. Why They Don’t Work Always!

On Focus

onfocus

Perhaps you think of onfocus and onblur events as a default behavior existing in any web page. This is not quite true! Onfocurs and onblur are well known in web developing (js) and are fired, of course, when the user tries to point something or leaves some element. Onfocurs is fired when the user either goes to an element with the Tab button on with the mouse. When the element is on focus, evidently, the onfocus event is fired. Actually you can see which element is on focus, like an anchor or input, when the element is outlined by the browser by default. In the same scenario, when some element has been on focus and than the user switches to another element, the onblur event is fired. Thus you may guess that this element is no longer on focus.

This in general are the onfocus/onblur events. The interesting part is that by default are known as built-in events in every page, but that is wrong.

Where Are My Events?

A typical use case is to take the code from some web page, where you’re sure this works perfectly, you can focus and blur element with no obstacle, but once you paste it inside your markup everything’s going wrong. Imagine you’ve the following markup (a typical search box text):

<input type="text" onblur="if(this.value=='') this.value = 'Search in This Site';" onfocus="if(this.value=='Search in This Site') this.value = '';" />

This works perfectly until you paste it to your site. And than nothing works correctly. Why? Where’s the problem?

Make Them Work

Actually the problem isn’t hiding somewhere in the markup above. It’s in the HTML definition. There are lots of web pages using strict HTML definition, that looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	...
</head>
<body>
	...

while you’ve to use the pure HTML definition to make onfocus/onblur work.

You’ve to switch to:

<html>
<head>
	...
</head>
<body>
	...

Than you can continue using these useful events!

Leave a Reply

Your email address will not be published. Required fields are marked *