0

Simple piece of jQuery that adds the class .typing to the <html> tag while the user is currently typing. I've tried several different things that all haven't worked, not sure how else to do this.

$('html').keypress(function(){
    $(this).addClass('typing');

    if  ( /* No key is pressed again in the next 0.5 seconds */ ) {
        $('.typing').removeClass('typing');
    }
});
2
  • please specify what are you actually asking - is it about implenting the condition after the if or is it why this script isn't working for you (document.ready stuff etc)? Commented Nov 27, 2011 at 21:52
  • the answer below already fixes this Commented Nov 27, 2011 at 21:54

2 Answers 2

5

Create a function which executes certain code after 0.5 seconds, using setTimeout (in conjunction with clearTimeout, to prevent multiple timeouts from be active at a time).

var timer;                  //Local variable to hold time-out reference
function refreshPress(){
    clearTimeout(timer);    //Prevent stacked time-outs, only one is allowed
    timer = setTimeout(function(){
        $('.typing').removeClass('typing');
    }, 500); //0.5 seconds
}

$('html').keypress(function(){
    $(this).addClass('typing');  //This line can also be merged with refreshPress
    refreshPress();              // Call refreshPress
});
Sign up to request clarification or add additional context in comments.

3 Comments

actually now that I try it out, after a couple of times typing it stops using the delay and just immediately add and removes it
@JamesKyle Show a fiddle with your code. Have you correctly implemented the code in the answer?
@JamesKyle You were missing timer = . Fixed fiddle: jsfiddle.net/UDhfU/31
1

Use setTimeout() and clearTimeout() instead of the if.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.