Learn about Keyboard and Mouse Events in AngularJS

keyboard and mouse events

keyboard and mouse events

In this tutorial, we’re going to go over all the keyboard and mouse events we can use with AngularJS. With AngularJS, you can bind mouse events to event handlers and pass the event as a parameter of the handlers. We’re going to start with a practical example. We’ll create a div with a controller and place an input box inside it. We’ll target the ng-blur event whenever a user clicks the mouse inside the input box.

In the JS, we’re going to give blur a default value of 0, like so:

Let’s add a number of other events, in the exact same way as ng-blur, like so:

An exception is ng-keydown, which passes an event to the Javascript  whenever the user presses any key on the keyboard.

Let’s give all of these a default value of 0 in the JS file:

With regards to ng-keydown, we need to find out what key was pressed – We pass the event as a parameter called ‘e’ to a function which handles it by converting the key code into letters and/or numbers.

Let’s organize the output:

This has been a run-down of all the events we can use. Let’s try to use the ng-mouseenter and ng-mouseleave directives in a different way. We’ll bind them to the mouseenter/mouseleave event handlers to display the coordinates at which the user enters/leaves an object.  The HTML:

We’ll give our object a unique id, <div id=”cube”></div>.
We’re going to use the help of jQuery to display the coordinates, like so:

keyboard event output

In summary, we’ve gone over all the mouse and key events we can use with Angular JS by giving a practical example for each of the directives. We have seen how simple it is to bind mouse events to event handlers using Angular directives, as well as passing the events as parameters. We finished off with an example in which we use jQuery as well as Angular to display mouse coordinates at the time of a mouse event.


Please enter your comment!
Please enter your name here