I have some inputs with floating labels over the top of them. The effect is basically, inside an email text input, it says ‘Enter your email’. As you click the input, the label fades away.
I have a working function for it all, but I have some repeating code.
IE:
My html looks like this:
<div id="action">
<form action="/" method="post" id="#register_form">
<input type="hidden" name="create" value="1" />
<div class="form-field">
<label for="register_name">Name (First & Last)</label>
<input id="register_name" class="form-text" type="text" name="name" tabindex="1"/>
</div>
<div class="form-field">
<label for="register_email">Enter your email</label>
<input id="register_email" class="form-text" type="text" name="email" tabindex="2"/>
</div>
<div class="form-field">
<label for="register_password">Password</label>
<input id="register_password" class="form-password" type="password" name="password" tabindex="3"/>
</div>
<button type="submit">Almost there!</button>
</form>
</div>
And the jquery looks like so:
$('#action input[type=text], #action input[type=password]').focus(function(){
// get this label
var this_id = $(this).attr('id');
$('label[for='+this_id+']').addClass('in_lighter');
}).blur(function(){
// get this label
var this_id = $(this).attr('id');
if($(this).val()==""){
$('label[for='+this_id+']').removeClass('in_lighter');
}
}).keyup(function(){
// get this label
var this_id = $(this).attr('id');
$('label[for='+this_id+']').fadeOut();
});
As you can see, the function does a few different things depending on whether its a focus, blur, or keyup. In each of those functions though, it grabs the id the selected input, then uses that to identify the label to work with. As you can see, I’m repeating this code 3 times:
// get this label
var this_id = $(this).attr('id');
Is there a better approach to this? A more streamlined method to achieve the same result?
Instead of:
You could do:
This would get the next previous element which was a label, so you wouldn’t need any id hookup then.