tags:

views:

180

answers:

1

Hi there,

I'm trying to add a class (.active) to a text field once the user starts typing. I got it to work somewhat with the following code, but for some reason the .active class is not applied immediately when the user starts typing, it's only applied after a second letter has been typed. Any ideas?

$(document).ready(function() {

    loginField = $('.field');

    loginField.live('keydown', function(){
        if ($(this).val()){
            $(this).addClass('active');     
        }
    });
}); 
+1  A: 

You want keyup here, updated based on comments:

$(document).ready(function() {    
    $('.field').live('keydown', function(){
      $(this).addClass('active');
    }).live('keyup', function() {
      $(this).toggleClass('active', $(this).val() != '');
    });
}); 

Your .live() is firing correctly, but the .val() doesn't change until keyup fires, keydown fires before the value is updated, so your if() isn't true until the 2nd key is pressed.

Nick Craver
Thanks for the tip, Nick. It's better with keyup, but since the .active class is only added after the user releases the key, it's still not immediate. Is there any way to have so the class added right when the user presses down on they key?
Simon
@Simon - It should be active whenever it has *any* text in there? or only when it's being edited and has text in there?
Nick Craver
@Nick option 2, when it's being edited and has text in there. I already have the rest of the js working for removing the .active class on blur.
Simon
@Simon - Try the updated example, this adds the class immediately regardless of value, then checks when the key is lifted and removes the class if the value's empty.
Nick Craver
@Nick - That worked! Thanks much.
Simon