Keyboard events in jQuery


In this lesson, you will learn about the jQuery keyboard events: Keydown() and Keyup() events. These events are generally used with keypress() event, which is fired when the key is pressed.

Introduction to Keyboard events in jQuery

The syntax for these events are:

Keydown(function(){});
Keyup(function(){});

The argument here is optional and if provided, executes every time the events are fired. You can also write these as .on("keydown", function(){}); or .on("keyup", function(){});

Example of Keyboard events in jQuery

In this example, we have created a simple form with one text field only. Each time the user puts the keyboard key down, the background color of the text box changes. And when the user releases the key, it goes to its original color.

Keyboard event example

When the user puts the key down, the color changes to pink and when releases it goes back to blue.

Keyboard event example

The HTML

<input type="text" name="txt" id="txt">

The CSS

label {
	width: 300px;
	display: block;
}

input {
	width: 80%;
	padding: 7px;
	background-color: #00A9FE;
	color: white;
}

The jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> 
<script>
    $(document).ready(function() {
        $("input").keydown(function() {
            $("input").css("background-color", "#fd6bb6");
        });
        $("input").keyup(function() {
            $("input").css("background-color", "#00A9FE");
        });
    }); 
</script>

With this code, you can see fast-changing background color with each key being pressed down and released. This may not seem a useful example, but to illustrate the concept, I tried to keep the example simple. But still, if you have any question, feel free to ask in the comment section below.

jQuery Select Event Tutorial Home jQuery Hover Event

 

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply