JavaScript Events
An event is something that happens on a web page: the visitor clicks a button, types in a field, moves the mouse, or the page finishes loading. JavaScript can listen for events and run code when they happen.
Common events
| Event | When it happens |
|---|---|
click | An element is clicked |
dblclick | Double click |
mouseover, mouseout | The mouse enters or leaves an element |
keydown, keyup | A key is pressed or released |
input | The value of an input changes while typing |
change | A field loses focus after its value changed, or a select changes |
submit | A form is submitted |
focus, blur | A field gets or loses the cursor |
load | The page or an image has loaded |
scroll, resize | The page is scrolled or the window changes size |
Ways to handle an event
1. HTML attribute (old, avoid)
<button onclick="alert('Clicked!')">Click me</button>
2. Event handler property
<button id="btn">Click me</button>
<script>
document.getElementById("btn").onclick = function () {
console.log("Clicked!");
};
</script>
3. addEventListener (best)
<button id="btn">Click me</button>
<script>
document.getElementById("btn").addEventListener("click", function () {
console.log("Clicked!");
});
</script>
When the visitor clicks the button, the console shows:
Output of the above program is
Clicked!
addEventListener() is the best way, because you can add many handlers to the same event. Learn it in DOM EventListener.
The event object
The handler receives an event object with details, like which element was clicked and which key was pressed.
document.addEventListener("keydown", function (event) {
console.log("Key pressed: " + event.key);
});
Note:
If you press the letter a, the console shows Key pressed: a.
Summary
- An event is something that happens on the page.
- Use
addEventListener("event", handler)to react to it. - The handler gets an event object with details.
- Next: JavaScript HTML DOM.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |