Joakim Melin
Joakim Melin

Reputation: 175

keyup only works one time

$("#hi").keypress(function() {
    $(".hi").html("Writing...");
});
$('#hi').keyup(function() {
    $(".hi").delay(1000).queue(function() {
        $(this).html("");
    });
});

When I type like "Hello" in a textbox (#hi) the keyup only works for the first letter and then it won't disappear.

Upvotes: 2

Views: 634

Answers (2)

Andy Ray
Andy Ray

Reputation: 32066

You're blocking the queue by not calling next

As of jQuery 1.4, the function that's called is passed another function as the first argument. When called, this automatically dequeues the next item and keeps the queue moving. We use it as follows:

$("#test").queue(function(next) {
    // Do some stuff...
    next();
});

Upvotes: 3

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You could use a timeout instead of a delay:

var timeout;
$("#hi").keypress(function() {
    // Clear any previous timeout
    clearTimeout(timeout);

    // Apply the writing text
    $(".hi").html("Writing...");

    // Remove the text after one second if no more key is pressed until then
    timeout = setTimeout(function () {
       $(".hi").html("");
    }, 1000);
});​

Here is a working example: http://jsfiddle.net/tF7DH/1/

The idea here is that you set a timeout to remove the "Writing..." text one second after the key stroke. If a new key stroke is made within that second, the previous timeout is cleared and a new one is set. That way, the text will only be removed when the user has stopped typing for more than one second.

Upvotes: 3

Related Questions