I’ve been looking at this for the last few hours, and can’t really achieve what I’m looking for. I currently have the following two inputs:
<input type="text" id="username" value="USERNAME" onfocus="inputFocused(this)" onblur="inputBlurred(this)" />
<input type="password" id="password" value="PASSWORD" onfocus="inputFocused(this)" onblur="inputBlurred(this)" />
Initially, the inputs text is grey, and I have the following JavaScript functions onfocus and onblur:
var defaultInput = "";
function inputFocused(obj){
defaultInput = obj.value;
obj.value = "";
obj.style.color = "#000";
}
function inputBlurred(obj){
if(obj.value == ""){
obj.style.color = "#AAA";
obj.value = defaultInput;
}
}
I’m trying to devise a way so that once I start typing into a field, leave the field, then return, it will not clear the input again (since it will then contain something the user typed in it). I’ve thought of achieving this with some kind of variable that I can alternate between 1 and 0 depending on the state, but that seemed sloppy. Any insight for this JS novice is greatly appreciated.
In inputFocused, you are clearing the input field’s value regardless of any state. Maybe I am misunderstanding your intention, but why would you ditch the value when focusing the control?
Updated: Adding a ‘defaultTextValue‘ attribute to each element allows you to capture the input’s default value on the first focus event. The alternative is to use your document’s onLoad event to capture the default values. The snippet below clears the textboxes when they are focused and their value is the same as the default values they were initialized with. You might annoy users that have either a username of ‘username’ or a password of ‘password’, but you probably should anyways 😎