What Are JavaScript Events? See Examples in detail

Events in JavaScript are actions that happen in the browser, such as a user clicking a button, moving the mouse, typing on the keyboard, or loading a page. JavaScript allows you to respond to these events using event handlers.

This blog explains how events work and provides examples of the most common events.


1. What Is an Event?

An event is an interaction between the user and the browser. When an event occurs, you can write a function (event handler) to perform a specific task.


2. Adding Event Handlers

There are three main ways to handle events:

1. Inline HTML Attribute

<button onclick="alert('Button clicked!')">Click Me</button>

2. Using DOM Property

let btn = document.getElementById("myBtn");
btn.onclick = function() {
  alert("Button clicked!");
};

3. Using addEventListener (Recommended)

let btn = document.getElementById("myBtn");
btn.addEventListener("click", function() {
  alert("Button clicked!");
});

3. Common JavaScript Events

Mouse Events

  • click → when an element is clicked
  • dblclick → double-click
  • mouseover → mouse enters element
  • mouseout → mouse leaves element

Example:

let box = document.getElementById("box");
box.addEventListener("mouseover", function() {
  box.style.backgroundColor = "yellow";
});

Keyboard Events

  • keydown → when a key is pressed
  • keyup → when a key is released
  • keypress → when a key is pressed and held

Example:

document.addEventListener("keydown", function(event){
  console.log("Key pressed: " + event.key);
});

Form Events

  • submit → when a form is submitted
  • focus → when an input gains focus
  • blur → when an input loses focus

Example:

let form = document.getElementById("myForm");
form.addEventListener("submit", function(event){
  event.preventDefault(); // prevent form submission
  alert("Form submitted!");
});

Window Events

  • load → when the page finishes loading
  • resize → when the window size changes
  • scroll → when the user scrolls the page

Example:

window.addEventListener("resize", function() {
  console.log("Window resized!");
});

4. Event Object

The event object contains information about the event.

document.addEventListener("click", function(event){
  console.log("Clicked element:", event.target);
  console.log("X coordinate:", event.clientX);
  console.log("Y coordinate:", event.clientY);
});

Conclusion

Events make JavaScript interactive. By using event handlers, you can respond to user actions, update the UI dynamically, and create responsive web applications.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *