How to Use jQuery’s Keystroke Methods


jQuery’s Keystroke Methods

In This Article We Discuss About jQuery’s Keystroke Methods. Query has a few built-in keystroke methods that are all triggered by different stages of keys being pressed on a user’s keyboard. If you want to be able to keep track of how many keystroke a user makes, or if you want an event to be triggered as the result of a key being pressed (or released), then this methods can help you achieve those things. The keystroke methods that we’ll go over in this tutorial are .keypress(), .keydown(), and .keyup() — from their names you might be able to roughly gather what type of keystroke action it takes to trigger each of them.

.keypress()

The .keypress() method is triggered when a key is pressed down. This event can be used to keep track of how many times a user presses a key down within a certain time frame, or within a certain element (like an input or textbox field — the method can be used to keep track of not how many characters are within the element, but how many times the user makes a keypress).

Here’s how the syntax would look if you want to measure the amount of keypresses that occur within a particular textbox:

var i=0

$(“textbox”).keypress(function(){

console.log(i += 1);

})

.keydown()

The .keydown() method is actually very similar to the .keypress() method. While .keypress() is triggered when a key is pressed all the way down, .keydown() triggers an event when the key is just beginning to be pressed, or when its on the way down. If a key is on the way down, there’s good chance that it’s going to be pressed all the way down, but that’s not a guarantee, so even though .keydown() and .keypress() are extremely similar to each other, they shouldn’t necessarily be used interchangeably.

The syntax, however, is the same. If you want to keep track of the amount of times the keys are pressed down (rather than all the way), you can use the same function as the one in the example. For an idea of how you might do that, see the .keyup() example below.

.keyup()

Maybe you’ve guessed it by now, but if you haven’t, the .keyup() method is triggered when a key is on the way up — this usually happens after it’s been pressed all the way down. When a key is released, the event is triggered..

The syntax is similar to that of both the .keypress() and .keydown() methods. In the example below, see how you would use the method to trigger an event that would change the CSS of a particular element when a key is released (remember, this will happen when any key is released within an textarea field, you can’t restrict the event method to a particular key).

$(“textarea”).keyup(function(){

(“textarea”).css(“color”, “blue”);

})


 

Leave a Reply

Your email address will not be published. Required fields are marked *