jlmakes
jlmakes

Reputation: 2965

How do I trigger my Javascript form handlers on form auto-fill?

I've built a form similar to Twitter's login, ie. there's a <span> holding a label for each <input>... then on keypress, the label animates it's font-size to 0. It's a cool effect.

The problem I've noticed, is that if you use a form auto-filler, only the form that fired the initial keypress event correctly animates it's label--the other labels don't properly animate away, and thus overlap the input's value.

My question is this... how to compensate for this? What events are being fired when a form auto-filler enters input values, and more specifically, how would I utilize them with jQuery?

. . .

Sample form below:

<div class="name">
    <input class="name" name="name" type='text' value="<?php echo $name; ?>">
    <span>Full Name</span>
</div>

. . .

Sample jQuery below:

$(function(){
    // On document ready, check form fields
    $(':input').each(function() {
        if($(this).val() === "") {
            $(this).next('span').animate({fontSize:16},'fast');
        }
    });

    // On form focus, adjust colors
    $(':input').focus(function() {
        $(this).addClass('focus');
        $(this).next('span').addClass('focus');
    });

    // On keypress, remove label
    $(':input').keypress(function() {
        $(this).next('span').animate({fontSize:0},'fast',function(){
            $(this).hide();
        });
    });

    // On form blur, restore colors and label
    $(':input').blur(function() {
        $(this).removeClass('focus');
        $(this).next('span').removeClass('focus');
        if($(this).val() == '') {
            $(this).next('span').show().animate({fontSize:16},'fast');
        }
    });

    // Pass span 'click' event to input
    $('form span').click(function() {
        $(this).prev('input').trigger('focus');
    });
});

Upvotes: 5

Views: 2544

Answers (3)

Paul Irish
Paul Irish

Reputation: 49142

Considering using the https://github.com/tbosch/autofill-event library, which handles all the odd browser cases for you.

Upvotes: 1

Bart
Bart

Reputation: 6814

Sounds similar to this issue: How to bind to browser change of input field? (jQuery)

In essence, browsers do not seem recognize the onchange event when dealing with autofillers.

The best solution I've seen out there (and I know it is not ideal) is checking the field's value over and over again via an interval. You'll find some codez for the basic idea in the above linked "similar" question.

Upvotes: 1

Simon Stender Boisen
Simon Stender Boisen

Reputation: 3431

Did you try the change-event? http://api.jquery.com/change/

Upvotes: 0

Related Questions