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

EventWhen it happens
clickAn element is clicked
dblclickDouble click
mouseover, mouseoutThe mouse enters or leaves an element
keydown, keyupA key is pressed or released
inputThe value of an input changes while typing
changeA field loses focus after its value changed, or a select changes
submitA form is submitted
focus, blurA field gets or loses the cursor
loadThe page or an image has loaded
scroll, resizeThe 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.