Qiang
Qiang

Reputation: 656

Keyup() delaying

I am using the keyup function on JQuery to add a class to a div whenever the user presses a character or something and remove a class when they hit backspace. But the keyup function has a small delay. I have tried using keypress and it has no delays, however, it does not detect backspaces so I cant use it.

Does anyone know how to stop the delay on keyup or an alternative function that I could use?

Upvotes: 1

Views: 735

Answers (3)

Nope
Nope

Reputation: 22339

But the keyup function has a small delay. I have tried using keypress and it has no delays, however, it does not detect backspaces so I cant use it.

The small delay you experience is due to the fact that keyup doesn't trigger until the user releases the key.

If you do not want a delay use keydown instead.

$('#target').keydown(function(eventData) {

    if(eventData.which === 8){
        // Backspace was pressed
    } else {
        // another key was pressed
    }
});

DEMO

Upvotes: 1

webdeveloper
webdeveloper

Reputation: 17288

You taking about something like this?

$(document).ready(function() {
    var timer,
        container = $('p');

    function doSomething()
    {
        container.text(new Date());
    }

    $('#find').keyup(function() {
        clearTimeout(timer);
        timer= setTimeout(doSomething, 200);
    });
 });  

Demo: http://jsfiddle.net/tXJAz/

Upvotes: 1

Johan
Johan

Reputation: 35223

$(function(){

    $('html').keyup(function(e){

        var d1 = new Date().getMilliseconds();

        if(e.which === 8){
            alert('Backspace pressed, delay: ' + new Date().getMilliseconds() - d1) + 'ms';
        }   

    });
});

Upvotes: 1

Related Questions