So I was working on a new project and I wanted to use a descriptive text in my textbox so I wouldn’t need to display a label to keep the look a little more simple. Obviously I still have a label for the textbox for accessibility reasons, I just hide the label with CSS. Okay…this is harder to explain than I thought, so I’ll show you a picture.
This is what I’m talking about. I want to hide the descriptive text on focus and put it back on blur if nothing changed. So want to change the style and reset the value on focus and blur. We’ll start with the focus and here is the jQuery:
$("input").focus(function() {
if ($(this).val() == $(this).attr("title"))
$(this).val("").css('color', '#000');
});
What the above code says is for ALL input types onfocus do this function. The function says if this input value = this input’s title, then set the value to nothing and set the color style to black.
Simple enough right? Let’s look at the blur, which simply means out of focus.
$("input").blur(function() {
if ($(this).val() == "" || $(this).val() == $(this).attr("title"))
$(this).val($(this).attr("title")).css('color', '#666');
});
Okay, so this code says for ALL input types onblur do this function. The function says if this input value = nothing OR this input value = this input’s title then set this input value back to the title and change the color style to a gray.
So now anytime I want to set a descriptive text, I just need it to match the title of the input and I can use this script for all of it. We should be using the title attribute anyhow!
Please let me know if you have any questions or if you see anything that I can improve. Thanks for reading!