Highlighting text fields onfocus
Have you ever noticed that some web sites you visit have their text input fields display a different background color when you put your cursor inside (in focus) of the field, like this?
Well quite simply, this can be done two ways. The first, and easy way would be to use the CSS :focus pseudo class.
input:focus { background-color:#DEEFFF; }
The second, and slightly more cumbersome way would be to use the JavaScript onfocus/onblur method listeners, and then manipulate the element's onfocus event using style.backgroundColor.
<input type="text" onfocus="this.style.backgroundColor='#DEEFFF';"
onblur="this.style.backgroundColor='#FFFFFF';" />
In a perfect world, CSS would be the way to go, but the problem is that IE6 and below doesn't support the CSS :focus pseudo class. So this effect will not be seen by a lot of your visitors. And the JavaScript solution would have to be inserted into every single input field in order to work, so it's clearly not a very intuitive, or reasonable solution either.
The Solution
So what we will need is a JavaScript solution which will crawl through the entire document looking for any text input fields, and will apply a alternate background color onfocus–dynamically. Therefore, we would not need to insert any additional onfocus/onblur attributes, only call to an external JavaScript file.
<script src="highlight.js" type="text/javascript"></script>
function highlight() {
var elements = document.getElementsByTagName("input");
for (i=0; i < elements.length; i++) {
if(elements[i].getAttribute('type')=="text") {
elements[i].onfocus=function() {
this.style.borderColor='#5789C6';
this.style.backgroundColor='#D3E2FD';
};
elements[i].onblur=function() {
this.style.borderColor='#AABBCC';
this.style.backgroundColor='#E3F1FF';
};
}
}
}
window.onload = highlight;
The above code is a very simplified example of course, and just by looking at this script I'm sure you can tell that it could be easily modified to include textarea, select, and even other types of input fields.
Aug 05, 2007
Comments
thank you man! :)
Thank-you! This is exactly what I was looking for to change some default input field text. Great explanation.
My vote is to ignore IE6 in this case and use the CSS version. Since it is a cosmetic enhancement (not to underestimate the value as such) but IE6 users would gracefully just not notice anything. I'd rather have lighter, simpler code.
Thank you. This was extremely simple, and your explanation was very concise and complete.
I wish all W3C docs were as good and clear as their section on selectors
Very Good script its useful and its in CSS and JS

Write a comment
* = required field