jQuery

jQuery keypress Example

The aim of this example is to show you how to capture keyboard keys events, specifically when a key is pressed. In jQuery, there is a method for that, .keypress(). The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs.

In other words, it binds an event handler to the “keypress” JavaScript event, or triggers that event on an element.

This is useful to enhance user interaction like when writing a password and want to tell the user that the length should be 6 or more characters, or when trying to have an autocomplete search box.
 
 

1. Basic Document Setup

To begin, create a new HTML document and add the following basic syntax inside:

<!DOCTYPE html>
<html>
<head>
	<title>jQuery Keypress Example</title>
</head>
<body>

<!-- HTML SECTION  -->


<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">

</script>

</body>
</html>

Note that jQuery library is linked locally, so you need to download and link it too, by clicking here.

2. .keypress() Basic Application

First, create a new input element and a paragraph, p in your HTML, which are going to be the element where we’ll write something and the element that will count how many times we’ve pressed a key on the keyboard respectively.

<!-- HTML SECTION  -->
Write something: <input type="text">
<p>Keypresses: <span>0</span></p>

Next, in the JS section, let’s start a variable i=0 and then increment it on every keypress like so:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
var i = 0;
$(document).ready(function(){
    $("input").keypress(function(){
        $("span").text(i += 1);
    });
});
</script>

The result would be:
keypress1
That was a basic application of the .keypress() method where we integrated a function inside the method to cound how many times we had a keypress and show it to the user. This syntax (.keypress() is a shorthand for .on("keypress", function(){});), so either of them will work in your real-life examples.

3. Practical Examples

Below, let’s have a look on two significant examples, one of which a function one, and the other, a design consideration.

3.1 A Functional Example

Here, we’ll simulate a password field where you should enter 6 or more characters for the password to be valid. First, format your HTML a bit different to have a password input field and a paragraph like this:

<!-- HTML SECTION  -->
Password: <input type="password">
<p></p>

Now, increment the variable i (which was initially set to 0) everytime there is a keypress. Then, add an if statement, where you check if the length of the password (times any key is pressed) is less than 6, and if it is true, then tell the user this password is not valid. Otherwise, accept the password.

<script type="text/javascript">
<!-- JAVASCRIPT SECTION  -->
var i = 0;
$(document).ready(function(){
    $("input").keypress(function(){
        i+=1;
        if (i<6) {
            $("p").text("Password must be 6 or more characters long!");
        }
        else {
            $("p").text("Your password is valid!");
        }
    })
});
</script>

Let’s see this in action:
A functional example

3.2 A Design Consideration with Keypress

Keypress is also used to relate design elements when capturing a kerpress, like a loading animation on a search box. So this example has taken me pretty much time so the code might be a bit longer than until now, but the idea remains, using the keypress event listener to add a loading animation.

In the HTML section, I’ve created the search structure:

 <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/animate.css">

  <div class="container">
    <div class="search">
    <input type="text" placeholder="Search for anything...">
    <i class="glyphicon glyphicon-search"></i>
    <div style="display: none; opacity: 0.8" class="loader"></div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>

Notice some links are local ones, but you’ll get everything in your source download files.

The next part was designing a nice search box in CSS: (this might not be of your interest)

    <style type="text/css">
.container {
  margin-top: 5em;
}

input {
  border: transparent;
  width: 35px;
  height: 3em;
  position: absolute;
  padding-left: 3em;
  background-color: #D35400;
  border-radius: 0.5em;
}

.search {
  color: white;
}

::-webkit-input-placeholder {
  color: white;
}

.search {
  /*float: left;*/
  max-width: 500px;
}

.glyphicon {
  position: relative;
  padding: 1em;
  color: white;
}

.loader:before,
.loader:after,
.loader {
  border-radius: 50%;
  width: 0.8em;
  height: 0.8em;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation: load7 1.5s infinite ease-in-out;
  animation: load7 1.5s infinite ease-in-out;

}
.loader {
  font-size: 15px;
  margin: auto 30em;
  position: absolute;
  top: 3.2em;
  text-indent: -9999em;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  -webkit-animation-delay: -0.08s;
  animation-delay: -0.08s;

}
.loader:before {
  left: -1.2em;
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}
.loader:after {
  left: 1.2em;
}
.loader:before,
.loader:after {
  content: '';
  position: absolute;
  top: 0;

}
@-webkit-keyframes load7 {
  0%,
  80%,
  100% {
    box-shadow: 0 2.5em 0 -1.3em #fff;
  }
  40% {
    box-shadow: 0 2.5em 0 0 #fff;
  }
}
@keyframes load7 {
  0%,
  80%,
  100% {
    box-shadow: 0 2.5em 0 -1.3em #fff;
  }
  40% {
    box-shadow: 0 2.5em 0 0 #fff;
  }
}
</style>

The JS section, is also more of a web designer work, but focus on the keypress method. It is used to trigger the .loader class, which contains the css animation, giving a very nice idea of something that is loading while you’re typing:

<script type="text/javascript">
<!-- JAVASCRIPT SECTION  -->
      $('.search').one('mouseover',function(){
         $( "input" ).animate({
          width: 500,
          padding: 12
        }, 300 );
         $('.glyphicon').addClass('pull-right animated slideInRight');
      });
      $('input').keypress(function(){
        $('.glyphicon').removeClass('pull-right animated slideInRight').addClass('animated bounceIn');
        $(this).css('padding-left','3em');
        $('.loader').show().fadeIn();
      }).keyup(function(){
        $(this).css('padding-left','3em');
      }).focusout(function(){
        $('.loader').hide().fadeOut();
      });
    </script>

Look at this outstanding result:
keypress3

4. Conclusion

To conclude, the .keypress() event is a great way to add functionality when this listener captures a press on the keyboad. It is similar to the keydown event. The event occurs when a button is pressed down.

However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC). Use the keydown() method to also check these keys. Cases where keypress interactivity is needed vary by where it is to be used. However, it is getting more and more used in modern websites.

5. Download

Download
You can download the full source code of this example here: jQuery Keypress

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button