Nowadays it's very common to find websites "hiding" form labels in favor of input's default text. Even tough it's a cleaver idea, there is a better way to accomplish the same result without compromising accessibility.
First step is to create the form. I usually have all my forms inside a list:
UPDATE: It's necessary to turn off the "autocomplete" so the inputs don't get messed up.
markup
<form action=""> <ul> <li> <label for="username">Username</label> <input id="username" type="text" autocomplete="off" /> </li> <li> <label for="password">Password</label> <input id="password" type="password" autocomplete="off" /> </li> <li> <input type="submit" value="login" /> </li> </ul> </form>
Don't forget the "for" attribute, the script will rely on it. Go ahead and add the following CSS:
CSS
form li { position: relative; } label { position: absolute; top: 5px; // adjust as needed left: 5px; } //remove absolute position if the label comes after //the input. Eg. a checkbox with a text next to it input + label { position: static; }
Now the final touch. With some jQuery magic, lets make the label disappear on focus.
jQuery
//loop through all text inputs, password inputs and textarea var inputs = $('input[type="text"], textarea, input[type="password"]'); // remove label on focus inputs.focus(function(){ $('label[for="'+$(this).attr('id')+'"]').hide(); }); inputs.blur(function(){ var that = $(this); if (that.val() == ""){ $('label[for="'+that.attr('id')+'"]').show(); } }); inputs.blur();
Comments
leave a commentits very usefull, thank you for sharing !