How could I be doing this jquery function a bit better? -


i have inputs floating labels on top of them. effect basically, inside email text input, says 'enter email'. click input, label fades away.

i have working function all, have repeating code.

ie:

my html looks 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 &amp; 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 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 jquery looks so:

$('#action input[type=text], #action input[type=password]').focus(function(){      // label     var this_id = $(this).attr('id');      $('label[for='+this_id+']').addclass('in_lighter');   }).blur(function(){      // label     var this_id = $(this).attr('id');      if($(this).val()==""){         $('label[for='+this_id+']').removeclass('in_lighter');     }  }).keyup(function(){       // label     var this_id = $(this).attr('id');      $('label[for='+this_id+']').fadeout();   }); 

as can see, function few different things depending on whether focus, blur, or keyup. in each of functions though, grabs id selected input, uses identify label work with. can see, i'm repeating code 3 times:

    // label     var this_id = $(this).attr('id'); 

is there better approach this? more streamlined method achieve same result?

instead of:

var this_id = $(this).attr('id'); $('label[for='+this_id+']').addclass('in_lighter'); 

you do:

$(this).prev("label").addclass('in_lighter'); 

this next previous element label, wouldn't need id hookup then.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -