JavaScript Events

JavaScript Events

JavaScript events are a way for JavaScript to interact with users by reacting to things that happen in the browser. These events are triggered by user actions or browser actions, such as clicking a button, loading a page, moving the mouse, resizing the browser window, or submitting a form.

1. What are Events?

An event is a signal sent to notify the program that something has happened. JavaScript can "listen" for these events and execute code in response.

Common Examples of Events:

  • Mouse Events: click, dblclick, mousemove, mouseenter, mouseleave
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, change, input, focus, blur
  • Window Events: load, resize, scroll, unload
  • Document Events: DOMContentLoaded, visibilitychange

2. How to Handle Events

JavaScript provides several ways to handle events:

  • Inline HTML attributes (less recommended)
  • DOM Element Property (commonly used)
  • Event Listeners (preferred)

3. Examples

Example 1: Using Inline HTML Attributes

	<!DOCTYPE html>
	<html>
	<head>
	  <title>Inline Event Example</title>
	</head>
	<body>
	  <button onclick="alert('Button clicked!')">Click Me</button>
	</body>
	</html> 
		

Here, the onclick attribute directly specifies the JavaScript to run when the button is clicked.


Example 2: Using DOM Element Property

	<!DOCTYPE html>
	<html>
	<head>
	  <title>DOM Property Example</title>
	  <script>
		function showAlert() {
		  alert('Button clicked!');
		}

		window.onload = function () {
		  const button = document.getElementById('myButton');
		  button.onclick = showAlert;
		};
	  </script>
	</head>
	<body>
	  <button id="myButton">Click Me</button>
	</body>
	</html>	  
		

Here, the onclick property of the button element is set to a JavaScript function.


Example 3: Using addEventListener

	<!DOCTYPE html>
	<html>
	<head>
	  <title>Event Listener Example</title>
	  <script>
		document.addEventListener('DOMContentLoaded', () => {
		  const button = document.getElementById('myButton');
		  button.addEventListener('click', () => {
			alert('Button clicked!');
		  });
		});
	  </script>
	</head>
	<body>
	  <button id="myButton">Click Me</button>
	</body>
	</html>	  
		

The addEventListener method allows multiple event listeners to be added to the same event, providing more flexibility.


4. Event Object

The event object contains details about the event, such as the element that triggered it, the type of event, and other data.

Example: Accessing Event Properties

	<!DOCTYPE html>
	<html>
	<head>
	  <title>Event Object Example</title>
	  <script>
		document.addEventListener('DOMContentLoaded', () => {
		  const button = document.getElementById('myButton');
		  button.addEventListener('click', (event) => {
			alert(`Button clicked! Event type: ${event.type}`);
		  });
		});
	  </script>
	</head>
	<body>
	  <button id="myButton">Click Me</button>
	</body>
	</html>
		

5. Preventing Default Behavior

Some events, like clicking a link or submitting a form, have default browser behavior. You can prevent this behavior using the preventDefault() method.

Example: Preventing Form Submission

	<!DOCTYPE html>
	<html>
	<head>
	  <title>Prevent Default Example</title>
	  <script>
		document.addEventListener('DOMContentLoaded', () => {
		  const form = document.getElementById('myForm');
		  form.addEventListener('submit', (event) => {
			event.preventDefault();
			alert('Form submission prevented.');
		  });
		});
	  </script>
	</head>
	<body>
	  <form id="myForm">
		<input type="text" placeholder="Your Name">
		<button type="submit">Submit</button>
	  </form>
	</body>
	</html>		
		

6. Event Propagation

Events in the DOM propagate in three phases:

  • Capturing Phase: The event travels down from the root to the target element.
  • Target Phase: The event reaches the target element.
  • Bubbling Phase: The event bubbles back up to the root.

Example: Capturing and Bubbling

		<!DOCTYPE html>
	<html>
	<head>
	  <title>Event Propagation Example</title>
	  <script>
		document.addEventListener('DOMContentLoaded', () => {
		  const parent = document.getElementById('parent');
		  const child = document.getElementById('child');

		  parent.addEventListener('click', () => alert('Parent clicked'), true); // Capturing phase
		  child.addEventListener('click', () => alert('Child clicked')); // Bubbling phase
		});
	  </script>
	</head>
	<body>
	  <div id="parent" style="padding: 20px; border: 1px solid red;">
		Parent
		<div id="child" style="padding: 20px; border: 1px solid blue;">
		  Child
		</div>
	  </div>
	</body>
	</html>  
		

Summary

JavaScript events are fundamental for creating dynamic, interactive web pages. By using different techniques to attach event handlers and understanding how events propagate, you can effectively manage user interactions.

Previous Next