Events
When we talk about events in Javascript, it's about actions that happen inside the browser. Let's see a few examples of events:
| Event | Description |
|---|---|
| onclick | When the user clicks (PCs) or touches (mobile devices) an element in the page. |
| onchange | When an HTML element changes. It's commonly used with form fields. |
| onmouseover | When the user moves the cursor over an element. |
| onmouseout | When the user moves the cursor out of an element. |
| onkeydown | When some key is pressed. |
We can tell the browser which function should be executed when those events are detected. This will open a new door for us because now we'll be able to interact with the user.
onclick, onmouseover e onmouseout
Let's see a few basic examples:
HTML:
<button id="click-me">Click here</button>
<button id="hover-me">Move the cursor over here</button>
<button id="leave-me">Move the cursor out of here</button>
Javascript:
document.getElementById("click-me").onclick = function() {
alert('You clicked the button');
};
document.getElementById("hover-me").onmouseover = function() {
alert('You moved the cursor over the button');
};
document.getElementById("leave-me").onmouseout = function() {
alert('You moved the cursor out of the button');
};
onkeydown
The onkeydown event can be applied to a specific element like a form field, or to the document object. Let's see the example below.
document.onkeydown = function() {
alert('You pressed a key');
};
It's also possible to monitor only a specific key. First we need to know how Javascript recognizes which key has been pressed. For this let's use the event object to get some information about it:
document.onkeydown = function(event) {
alert('You pressed the following key: ' + event.keyCode);
};
The keyCode property returns the Unicode of the pressed key.
This way we can see that the code for letter 'a' is 65. With this information we can create something that will only fire when this specific key has been pressed.
document.onkeydown = function(event) {
if(event.keyCode == '65') {
alert("Do something if letter 'a' is pressed.");
}
};
Event manipulation via html attribute
In the examples above we've been using the dom elements to set the events in the Javascript code. We can also set those events using HTML attributes:
<button onclick="show_alert()">Click here</button>
Now we just need to create the function to be executed when the event is detected.
function show_alert() {
alert('You clicked the button');
}