Last active
January 17, 2016 17:13
-
-
Save yakovsh/7b748e21e5ff825be4d6 to your computer and use it in GitHub Desktop.
Inobstrusive Form Field Highlighting in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* One of the recent problem that I ran across at work is an easy way to do highlighting for form fields. | |
* Of course the best way would be CSS 2 | |
* (as shown here [http://www.cssdrive.com/index.php/examples/exampleitem/focus_pseudo_class/]) but alas, | |
* IE does not support that. | |
* | |
* The alternative is JavaScript onFocus and onBlur method. However, one thing which I also wanted to avoid | |
* is changing over 200 different pages in our system to add those in. So instead, I wrote a simple piece of | |
* Javascript which attaches the event handlers on the fly. The best part about this is that the actual form | |
* does not need to be changed - just include the Javascript on the bottom of your webpage. The code is as follows | |
*/ | |
var fields = document.body.getElementsByTagName("INPUT"); | |
for(i=0; i < fields.length; i++) { | |
if(fields[i].type == 'text' || fields[i].type == 'password') { | |
fields[i].onfocus = highlightOn; | |
fields[i].onblur = highlightOff; | |
} | |
} | |
/* The two highlight functions are as follows: */ | |
function highlightOn() { | |
this.style.border = '1px solid blue'; | |
this.style.backgroundColor = 'white'; | |
} | |
function highlightOff() { | |
this.style.border = '1px groove #7A7E7C'; | |
this.style.backgroundColor = '#EEEEEE'; | |
} | |
/* And here is a real example */ | |
var fields = document.body.getElementsByTagName("INPUT"); | |
for(i=0; i < fields.length; i++) { | |
if(fields[i].type == 'text' || fields[i].type == 'password') { | |
fields[i].onfocus = highlightOn; | |
fields[i].onblur = highlightOff; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment