Handling Events in JavaScript

The magic of interactive web pages lies in their ability to respond to user actions and browser events. JavaScript equips developers with the tools to capture these events and execute corresponding code, breathing life into web experiences. This chapter delves into the world of event handling in JavaScript, providing a comprehensive guide from basic concepts to advanced techniques.

Understanding Events

Event Types: JavaScript supports a vast array of built-in events encompassing user interactions (clicks, key presses, mouse hovers), form submissions, window resizing, and more. You can even define custom events for specialized interactions within your application.

Event Bubbling and Capturing: Events typically propagate (bubble) up the DOM tree, from the target element where they originate to its parent elements, and so on, until they reach the document object. Alternatively, event capturing allows handlers to be registered at a higher level in the DOM tree and executed first before bubbling occurs.

Event Handling Mechanisms

Inline Event Handlers

(HTML Event Attributes):
Syntax:

				
					<button onclick="handleClick()">Click Me</button>

				
			

Explanation:

 Inline event handlers are directly assigned to HTML elements using attributes like onclickonmouseoveronsubmit, etc. When the event occurs, the specified JavaScript code within the attribute value is executed. This approach has limitations in maintainability and code organization.

Example:

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

				
			

Output: 

Clicking the button displays an alert box with the message “Button Clicked!”.

Event Listeners (addEventListener Method):

Syntax:

				
					element.addEventListener(eventName, functionName, useCapture);

				
			
  • element: The HTML element to which the event listener is attached.
  • eventName: The name of the event (e.g., “click”, “mouseover”, “submit”).
  • functionName: The JavaScript function to be invoked when the event occurs.
  • useCapture (optional): A Boolean value indicating whether to use event capturing (true) or bubbling (false, default).
  • Explanation: Event listeners provide a more flexible and robust approach to event handling. They allow you to:
    • Attach multiple handlers to a single element.
    • Dynamically add or remove handlers.
    • Specify the capture phase for event propagation.

Example:

				
					

<button id="myButton">Click Me</button>

				
			
				
					


const button = document.getElementById('myButton');
button.addEventListener('click', function() {
    alert('Button Clicked (using addEventListener)');
});

				
			

Output: Clicking the button displays an alert box with the message “Button Clicked (using addEventListener)”.

The DOM Event Object (Event Parameter):

  • Explanation: When an event handler function is invoked, it typically receives an event object as an argument. This object provides a wealth of information about the event, such as:
    • type: The event type (e.g., “click”, “mouseover”).
    • target: The element that triggered the event.
    • currentTarget: The element to which the event listener is attached (might differ in capturing/bubbling).
    • preventDefault(): A method to prevent the default behavior of the event (e.g., preventing form submission).
    • stopPropagation(): A method to stop the event from propagating further up the DOM tree.

Example (using preventDefault()):

				
					

<form id="myForm">
  <input type="submit" value="Submit">
</form>

				
			
				
					

const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent default form submission
    alert('Form submission prevented!');
});

				
			

Advanced Event Handling Techniques

Event Delegation:

Concept: Event delegation is an optimization technique that leverages the event bubbling mechanism. Instead of attaching event listeners to every individual element within a container, you can attach a single listener to the container and examine the event.target property within the handler to determine the specific element that triggered the event. This approach can improve performance, especially when dealing with dynamically generated content.

Example:

				
					

<ul id="itemsList">
  <li>Item 1</li>
  <li

				
			
				
					

const itemsList = document.getElementById('itemsList');

itemsList.addEventListener('click', function(event) {
  const clickedItem = event.target; // Identify the clicked element
  if (clickedItem.tagName === 'LI') {
    alert('Item clicked: ' + clickedItem.textContent);
  }
});


				
			

Explanation:

    1. We attach a single event listener to the itemsList container element.
    2. When an item (LI element) within the list is clicked, the event bubbles up to the container.
    3. The event.target property reveals the element that actually triggered the event.
    4. By checking if event.target.tagName is “LI”, we can ensure we’re only handling clicks on list items.

Custom Events:

Concept: JavaScript allows you to define and dispatch your own custom events to facilitate communication between different parts of your application. This is particularly useful for building reusable components and decoupling event handling logic from specific elements.

Example:

				
					// Define a custom event
const myCustomEvent = new Event('myEvent');

// Function to dispatch the event from anywhere
function triggerCustomEvent() {
  document.dispatchEvent(myCustomEvent);
}

// Event listener for the custom event
document.addEventListener('myEvent', function() {
  alert('Custom event received!');
});

// Trigger the event from a button click
const triggerButton = document.getElementById('triggerButton');
triggerButton.addEventListener('click', triggerCustomEvent);

				
			

Explanation:

    1. We create a new Event object using the new Event() constructor, providing a custom event name (“myEvent”).
    2. A function triggerCustomEvent() is defined to dispatch the event using document.dispatchEvent(myCustomEvent).
    3. An event listener is attached to the document object to handle the myEvent.
    4. The triggerButton is assigned a click event listener that calls triggerCustomEvent() when clicked, effectively dispatching the custom event.

Keyboard Events:

  • Concept: JavaScript provides a range of events for handling keyboard interactions, such as keydownkeyup, and keypress. These events enable you to capture key presses, releases, and specific characters typed, allowing you to create keyboard shortcuts, dynamic search suggestions, and form validation based on user input.

Example (using keydown for keyboard shortcuts):

				
					

<input type="text" id="searchInput">

				
			
				
					

const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keydown', function(event) {
  if (event.ctrlKey && event.key === 'F') {
    alert('Search shortcut activated!');
  }
});

				
			

Explanation:

    1. We attach a keydown event listener to the searchInput element.
    2. Inside the handler, we check if the ctrlKey (Control key) is pressed along with the “F” key using event.ctrlKey and event.key.
    3. If the shortcut combination is detected, an alert is displayed.

Form Validation:

  • Concept: Event handlers play a crucial role in validating user input within forms. You can leverage events like submit and change to ensure data entered by the user meets specific criteria before submitting the form.

Example (using submit for form validation):

				
					

<form id="myForm">
  <input type="text" id="name" required>
  <input type="email" id="email" required>
  <button type="submit">Submit</button>
</form>


				
			
				
					

const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
  const nameInput = document.getElementById('name');
  const emailInput = document.getElementById('email');
  if (nameInput.value.trim() === '') {
    alert('Please enter your name!');
    event.preventDefault(); // Prevent form submission
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput.value)) {
    alert('Please enter a valid email address!');
    event.preventDefault();


				
			

Touch Events (for Mobile Devices):

  • Concept: With the rise of touch-enabled devices, JavaScript provides touch events like touchstarttouchmove, and touchend to handle touch interactions. These events allow you to create responsive interfaces that adapt to touch-based gestures like taps, swipes, and pinches.

Example (using touchstart for mobile menus):

				
					

<div id="mobileMenu">Menu</div>


				
			
				
					

const mobileMenu = document.getElementById('mobileMenu');
mobileMenu.addEventListener('touchstart', function() {
  // Toggle menu visibility (implementation depends on your UI framework)
});

				
			

Explanation:

    1. We attach a touchstart event listener to the mobileMenu element.
    2. Inside the handler, you would typically implement logic to toggle the visibility or behavior of the mobile menu based on your UI framework (e.g., displaying a hidden menu or activating a slide-in effect).

Categories of events

There are several categories of events that cover a wide range of user interactions and browser behaviors. Here’s a breakdown of some common event types

Mouse Event

Event TypeDescriptionExample Usage
clickTriggered on a single mouse click (left click by default)Button clicks, image clicks
dblclickTriggered on a double clickSelecting text for editing
mousedownTriggered when the mouse button is pressed down (any button)Dragging elements
mouseupTriggered when the mouse button is released (any button)Dropping elements
mouseoverTriggered when the mouse pointer enters an element's boundariesTooltips, element highlighting on hover
mouseoutTriggered when the mouse pointer leaves an element's boundariesRemoving tooltips, element unhighlighting on hover
mousemoveTriggered when the mouse pointer moves over an element (continuously while hovered)Real-time drawing, element tracking during movement

Click:

				
					const button = document.getElementById('toggleButton');
button.addEventListener('click', function() {
  const content = document.getElementById('content');
  content.classList.toggle('hidden'); // Toggles the visibility of the content element
});

				
			

Explanation: This code snippet first retrieves a button element with the ID “toggleButton”. It then attaches a click event listener to the button. When the button is clicked, the function within the listener is triggered. This function retrieves the content element (e.g., a div) and toggles its “hidden” class using classList.toggle. This allows you to show or hide content based on button clicks.

Double Click:

				
					const image = document.getElementById('productImage');
image.addEventListener('dblclick', function() {
  image.src = 'larger-image.jpg'; // Changes the image source on double-click
});

				
			

This JavaScript code snippet attaches an event listener to an image element identified by the ID ‘productImage’. When a double-click event (‘dblclick’) occurs on this image, the code within the event listener executes. Specifically, it updates the image source (`src` attribute) to display a larger image, assuming there exists an image file named ‘larger-image.jpg’. This functionality could be utilized, for instance, to provide users with an expanded view of a product image when they double-click on it.

Mousedown

				
					<button id="myButton">Click Me</button>

				
			
				
					const button = document.getElementById("myButton");

button.addEventListener("mousedown", function() {
  button.style.backgroundColor = "red"; // Change color to red on mousedown
});

button.addEventListener("mouseup", function() {
  button.style.backgroundColor = "blue"; // Change color back to blue on mouseup (optional)
});

				
			

Explanation:

  1. HTML Button: We have a button with the ID myButton in our HTML.
  2. Select Button: We use document.getElementById in JavaScript to get a reference to this button.
  3. Mousedown Event: We attach a mousedown event listener to the button.
  4. Change Color on Press: Inside the event handler, when the button is pressed down, we change the background color of the button to red using button.style.backgroundColor = "red".
  5. Optional Mouseup (for visual feedback): We can optionally add a mouseup event listener to change the color back to blue (or any desired color) when the mouse button is released.

This is a basic example demonstrating how mousedown can be used to trigger an immediate visual change upon pressing a button.

Mouseup

				
					<div id="alertBox">Click and Release Here</div>

				
			
				
					const alertBox = document.getElementById("alertBox");

alertBox.addEventListener("mousedown", function() {
  console.log("Mouse Button Pressed Down"); // Optional for debugging
});

alertBox.addEventListener("mouseup", function() {
  alert("Mouse Button Released Inside Alert Box!");
});

				
			

Explanation:

  1. HTML Element: We have a div element with the ID alertBox where the user can click.
  2. Select Element: We use document.getElementById to get a reference to the alertBox.
  3. Mousedown (Optional): We add a mousedown event listener that logs a message to the console (optional, useful for debugging).
  4. Mouseup Event: The key part is the mouseup event listener attached to the alertBox.
  5. Alert on Release: When the mouse button is pressed down and then released within the alertBox element, an alert message is displayed.

Important Note:

This example showcases mouseup working within the same element. If the user clicks down inside the alertBox and releases the mouse button outside of it, the alert won’t be triggered. This demonstrates that mouseup fires only when the button is released within the element where the mousedown event was initially triggered

Mouseover

				
					<div id="hoverBox">Hover Over Me!</div>

				
			
				
					const hoverBox = document.getElementById("hoverBox");

hoverBox.addEventListener("mouseover", function() {
  hoverBox.style.backgroundColor = "lightblue"; // Change background color on hover
});

hoverBox.addEventListener("mouseout", function() {
  hoverBox.style.backgroundColor = "white"; // Change background color back to white on mouseout
});

				
			

Explanation:

  1. HTML Element: We have a div element with the ID hoverBox in our HTML.
  2. Select Element: We use document.getElementById to get a reference to the hoverBox in JavaScript.
  3. Mouseover Event: We attach a mouseover event listener to the hoverBox.
  4. Change Color on Hover: Inside the mouseover event handler, when the mouse pointer enters the hoverBox, we change its background color to light blue using hoverBox.style.backgroundColor = "lightblue".
  5. Mouseout Event: We attach a mouseout event listener to the hoverBox.
  6. Change Color Back on Out: Inside the mouseout event handler, when the mouse pointer leaves the hoverBox, we change its background color back to white using hoverBox.style.backgroundColor = "white".

This code creates a simple visual feedback for the user by changing the background color of the element when they hover over it.

Mouseout

				
					<div id="messageBox">Move your mouse!</div>

				
			
				
					const messageBox = document.getElementById("messageBox");

messageBox.addEventListener("mouseout", function() {
  console.log("Mouse left the message box!");
});

				
			

Explanation:

  1. We have a div element with the ID messageBox.
  2. JavaScript grabs a reference to it using document.getElementById.
  3. An event listener for mouseout is attached to messageBox.
  4. When the mouse pointer exits the messageBox (including its borders), the function logs a message to the console (you can replace this with any action).

In a nutshell: mouseout detects when the mouse leaves an element and lets you react to it!

MouseMove

				
					<div id="drawingArea">Draw here!</div>

				
			
				
					const drawingArea = document.getElementById("drawingArea");

drawingArea.addEventListener("mousemove", function(event) {
  console.log("Mouse X:", event.offsetX, "Mouse Y:", event.offsetY);
  // Or perform some other action based on mouse position
});

				
			

Key Points:

  • mousemove fires repeatedly as the mouse moves within the element.
  • The event object (event) provides information about the mouse’s position relative to the element using properties like offsetX and offsetY.
  • This event is often used for creating interactive experiences that respond to the mouse’s continuous movement.

This explanation focuses on the core functionality of mousemove within an HTML element.

Keyboard Event

Event TypeDescriptionExample Usage
keydownTriggered when a key is pressed downKeyboard shortcuts
keyupTriggered when a key is releasedDetecting when a key is no longer pressed
keypressTriggered when a character is typed (may not be consistent across all browsers)Input validation, live character filtering

keydown

Trigger:

  • This event fires when a physical key on the keyboard is pressed down (held down).
  • It occurs repeatedly if the key is held down for a long duration (auto-repeat behavior).

Action:

  • Useful for registering keyboard shortcuts or triggering actions when a specific key is pressed.
  • The event object (event) provides information about the pressed key, including its code (event.code), which is more reliable than the older keyCode property.

Example Usage:

				
					document.addEventListener("keydown", function(event) {
  if (event.code === "Escape") {
    console.log("Escape key pressed!");
    // Perform an action, like closing a modal window
  } else if (event.code === "Enter") {
    console.log("Enter key pressed!");
    // Perform an action, like submitting a form
  }
});

				
			

keyup

Trigger:

  • This event fires when a previously pressed key is released (lifted up).

Action:

  • Useful for detecting when a key is no longer being pressed and potentially performing actions based on that.
  • Can be used in combination with keydown for more complex interactions.

Example Usage:

				
					document.addEventListener("keydown", function(event) {
  if (event.code === "Shift") {
    isShiftPressed = true;
  }
});

document.addEventListener("keyup", function(event) {
  if (event.code === "Shift") {
    isShiftPressed = false;
  }
});

// Now you can use the `isShiftPressed` variable to control behavior based on the Shift key state

				
			

keypress (deprecated)

Trigger:

  • This event used to fire when a character key was pressed down, held, and then released (similar to typing a character).

Important Note:

  • Due to inconsistencies in behavior across browsers, keypress is considered deprecated.
  • It might not reliably capture certain characters (e.g., accented characters) or handle modifier keys (Shift, Ctrl, Alt) consistently.

Example (for illustration purposes only):

				
					document.addEventListener("keypress", function(event) {
  console.log("Character typed:", event.key); // Might not be reliable
});

// User types "h"
// Console might log: "h" (if reliable in this browser)

				
			

Alternative Approaches (Recommended):

Since keypress is deprecated, here are more reliable methods for character input detection:

keydown + keyup Combination:

    • Capture the key press with keydown to identify the pressed key.
    • Use keyup to confirm the key release and potentially validate the typed character.

Choosing the Right Approach:

  • If you need to handle specific key presses (like arrow keys or function keys), keydown or keyupmight be more suitable.
  • If you only care about the final typed characters, input can be a simpler solution.
				
					document.addEventListener("keydown", function(event) {
  if (event.key !== "Shift" && event.key !== "Control" && event.key !== "Alt") { // Exclude modifier keys
    characterBuffer += event.key; // Store the pressed character
  }
});

document.addEventListener("keyup", function(event) {
  if (characterBuffer.length > 0) {
    console.log("Typed character:", characterBuffer);
    characterBuffer = ""; // Reset buffer for next character
  }
});

// User types "h"
// Console logs: "h" (more reliable than using keypress alone)

				
			

Form Event

Event TypeDescriptionExample Usage
submitTriggered when a form is submitted (e.g., clicking a submit button)Validating form data before submission
changeTriggered when the value of an element within a form changes (e.g., input field, select box)Updating form fields based on user input
focusTriggered when an element receives focus (e.g., clicking on an input field)Highlighting input fields, accessibility features
blurTriggered when an element loses focus (e.g., clicking outside an input field)Validating input after focus is lost

Submit Event

Here’s an example of the submit event triggered when a form is submitted in JavaScript:

				
					

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <br>
  <button type="submit">Submit</button>
</form>

				
			
				
					

const form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
  // Prevent default form submission behavior (optional)
  event.preventDefault();

  // Get form data
  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;

  // Validate form data (optional)
  if (name === "" || email === "") {
    alert("Please fill in all required fields.");
    return; // Prevent further code execution if validation fails
  }

  // Simulate form submission (e.g., sending data to a server)
  console.log("Form submitted successfully!");
  console.log("Name:", name);
  console.log("Email:", email);

  // You can replace the above with actual form submission logic
  // (e.g., using AJAX or fetch API to send data to a server)
});

				
			

Explanation:

  1. HTML Form: We have a basic form with two input fields (name and email) and a submit button.
  2. Get Form Element: We use document.getElementById to get a reference to the form element (myForm).
  3. submit Event Listener: We attach a submit event listener to the form.
  4. Prevent Default (Optional): Inside the event handler, we can optionally call event.preventDefault() to prevent the default form submission behavior (which usually involves reloading the page).
  5. Get Form Data: We use document.getElementById to access specific input elements (name and email) and retrieve their values using the value property.
  6. Validation (Optional): We can add basic validation to check if required fields are filled.
  7. Simulate Submission: In this example, we simulate form submission by logging the data to the console. You would typically replace this with code that sends the data to a server using techniques like AJAX or the Fetch API.

This example demonstrates how the submit event allows you to capture form submission, access submitted data, perform validation, and potentially handle the submission process using JavaScript.

Change Event

Here’s an example of the change event triggered when the value of an input field in a form changes:

				
					


<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <br>
  <label for="age">Age:</label>
  <input type="number" id="age" name="age">
</form>


				
			
				
					// JavaScript Code

const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
const ageInput = document.getElementById("age");

// Add event listener for the change event on the name input field
nameInput.addEventListener("change", function(event) {
  console.log("Name changed to:", event.target.value);
});

// Add event listener for the change event on the email input field
emailInput.addEventListener("change", function(event) {
  console.log("Email changed to:", event.target.value);
});

// Add event listener for the change event on the age input field
ageInput.addEventListener("change", function(event) {
  console.log("Age changed to:", event.target.value);
});

				
			

Explanation:

  • HTML Form: We have a basic form with input fields for name, email, and age.
  • Get Input Elements: We use document.getElementById to get references to the input elements for name, email, and age.
  • Change Event Listeners: We attach change event listeners to each input field.
  • Event Handling: Inside the event handlers, we log the new value whenever the value of an input field changes.

This example demonstrates how you can capture changes in the values of form input fields using the change event in JavaScript.

Focus Event

 Here’s an example of the focus event triggered when an input field in a form receives focus:

				
					

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
</form>

				
			
				
					// JavaScript Code

const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");

// Add event listener for the focus event on the name input field
nameInput.addEventListener("focus", function(event) {
  console.log("Name input field has received focus.");
});

// Add event listener for the focus event on the email input field
emailInput.addEventListener("focus", function(event) {
  console.log("Email input field has received focus.");
});

				
			

Explanation:

  • HTML Form: We have a basic form with input fields for name and email.
  • Get Input Elements: We use document.getElementById to get references to the input elements for name and email.
  • Focus Event Listeners: We attach focus event listeners to each input field.
  • Event Handling: Inside the event handlers, we log a message indicating that the input field has received focus.

This example demonstrates how you can capture the focus event when an input field in a form receives focus using JavaScript.

BlurEvent

Here’s an example of the blur event triggered when an input field loses focus

				
					

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
</form>

				
			
				
					// JavaScript Code

const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");

// Add event listener for the blur event on the name input field
nameInput.addEventListener("blur", function(event) {
  console.log("Name input field has lost focus.");
});

// Add event listener for the blur event on the email input field
emailInput.addEventListener("blur", function(event) {
  console.log("Email input field has lost focus.");
});

				
			

Explanation:

  • HTML Form: We have a basic form with input fields for name and email.
  • Get Input Elements: We use document.getElementById to get references to the input elements for name and email.
  • Blur Event Listeners: We attach blur event listeners to each input field.
  • Event Handling: Inside the event handlers, we log a message indicating that the input field has lost focus.

This example demonstrates how you can capture the blur event when an input field in a form loses focus using JavaScript.

Window Event

Event TypeDescriptionExample Usage
loadTriggered when the entire page (including images, scripts, etc.) has finished loadingInitializing page elements after loading
resizeTriggered when the browser window is resizedResponsive layouts, adapting content to different sizes
scrollTriggered when the content within the window is scrolledInfinite scrolling, lazy loading content
unloadTriggered when the user navigates away from the page (less common due to security concerns)Saving user data before leaving the page

Load Event

Here’s an example of the submit event triggered when a form is submitted in JavaScript:

				
					
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Load Event Example</title>
</head>
<body>
  <h1>Welcome to My Website</h1>
   <script type="litespeed/javascript" data-src="script.js"></script> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script><script data-no-optimize="1">var litespeed_vary=document.cookie.replace(/(?:(?:^|.*;\s*)_lscache_vary\s*\=\s*([^;]*).*$)|^.*$/,"");litespeed_vary||fetch("/wp-content/plugins/litespeed-cache/guest.vary.php",{method:"POST",cache:"no-cache",redirect:"follow"}).then(e=>e.json()).then(e=>{console.log(e),e.hasOwnProperty("reload")&&"yes"==e.reload&&(sessionStorage.setItem("litespeed_docref",document.referrer),window.location.reload(!0))});</script><script data-optimized="1" type="litespeed/javascript" data-src="https://diginode.in/wp-content/litespeed/js/96d0e6d4ba93134cbdab615e06eb2824.js?ver=a1a89"></script><script>const litespeed_ui_events=["mouseover","click","keydown","wheel","touchmove","touchstart"];var urlCreator=window.URL||window.webkitURL;function litespeed_load_delayed_js_force(){console.log("[LiteSpeed] Start Load JS Delayed"),litespeed_ui_events.forEach(e=>{window.removeEventListener(e,litespeed_load_delayed_js_force,{passive:!0})}),document.querySelectorAll("iframe[data-litespeed-src]").forEach(e=>{e.setAttribute("src",e.getAttribute("data-litespeed-src"))}),"loading"==document.readyState?window.addEventListener("DOMContentLoaded",litespeed_load_delayed_js):litespeed_load_delayed_js()}litespeed_ui_events.forEach(e=>{window.addEventListener(e,litespeed_load_delayed_js_force,{passive:!0})});async function litespeed_load_delayed_js(){let t=[];for(var d in document.querySelectorAll('script[type="litespeed/javascript"]').forEach(e=>{t.push(e)}),t)await new Promise(e=>litespeed_load_one(t[d],e));document.dispatchEvent(new Event("DOMContentLiteSpeedLoaded")),window.dispatchEvent(new Event("DOMContentLiteSpeedLoaded"))}function litespeed_load_one(t,e){console.log("[LiteSpeed] Load ",t);var d=document.createElement("script");d.addEventListener("load",e),d.addEventListener("error",e),t.getAttributeNames().forEach(e=>{"type"!=e&&d.setAttribute("data-src"==e?"src":e,t.getAttribute(e))});let a=!(d.type="text/javascript");!d.src&&t.textContent&&(d.src=litespeed_inline2src(t.textContent),a=!0),t.after(d),t.remove(),a&&e()}function litespeed_inline2src(t){try{var d=urlCreator.createObjectURL(new Blob([t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1")],{type:"text/javascript"}))}catch(e){d="data:text/javascript;base64,"+btoa(t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1"))}return d}</script></body>
</html>

				
			
				
					// JavaScript Code (script.js)

// Add event listener for the load event on the window object
window.addEventListener("load", function(event) {
  console.log("Window has finished loading.");

  // You can perform additional tasks here after the window finishes loading
  // For example, fetching data, initializing components, etc.
});

				
			

Explanation:

  • HTML Structure: We have a basic HTML structure with a <script> tag at the end of the body, which refers to an external JavaScript file named script.js.
  • Window Load Event Listener: We attach a load event listener to the window object in the external JavaScript file.
  • Event Handling: Inside the event handler, we log a message indicating that the window has finished loading.
  • Additional Tasks: You can perform additional tasks within the event handler, such as fetching data from an external source, initializing components, or executing any other JavaScript code that needs to run after the window has finished loading.

This example demonstrates how you can capture the load event when the window finishes loading using JavaScript. This event is commonly used for initializing JavaScript code or performing tasks that require the DOM to be fully loaded.

Resize Event

Here’s an example of the resize event triggered when the window is resized:

				
					
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Resize Event Example</title><style>#resizeInfo {
      background-color: #f0f0f0;
      padding: 10px;
      position: fixed;
      bottom: 0;
      right: 0;
    }</style></head>
<body>
  <h1>Resize the Window</h1>
  <p>Resize the window to see the resize event in action.</p>
  
  <div id="resizeInfo"></div> <script type="litespeed/javascript" data-src="script.js"></script> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script><script data-optimized="1" type="litespeed/javascript" data-src="https://diginode.in/wp-content/litespeed/js/96d0e6d4ba93134cbdab615e06eb2824.js?ver=a1a89"></script><script>const litespeed_ui_events=["mouseover","click","keydown","wheel","touchmove","touchstart"];var urlCreator=window.URL||window.webkitURL;function litespeed_load_delayed_js_force(){console.log("[LiteSpeed] Start Load JS Delayed"),litespeed_ui_events.forEach(e=>{window.removeEventListener(e,litespeed_load_delayed_js_force,{passive:!0})}),document.querySelectorAll("iframe[data-litespeed-src]").forEach(e=>{e.setAttribute("src",e.getAttribute("data-litespeed-src"))}),"loading"==document.readyState?window.addEventListener("DOMContentLoaded",litespeed_load_delayed_js):litespeed_load_delayed_js()}litespeed_ui_events.forEach(e=>{window.addEventListener(e,litespeed_load_delayed_js_force,{passive:!0})});async function litespeed_load_delayed_js(){let t=[];for(var d in document.querySelectorAll('script[type="litespeed/javascript"]').forEach(e=>{t.push(e)}),t)await new Promise(e=>litespeed_load_one(t[d],e));document.dispatchEvent(new Event("DOMContentLiteSpeedLoaded")),window.dispatchEvent(new Event("DOMContentLiteSpeedLoaded"))}function litespeed_load_one(t,e){console.log("[LiteSpeed] Load ",t);var d=document.createElement("script");d.addEventListener("load",e),d.addEventListener("error",e),t.getAttributeNames().forEach(e=>{"type"!=e&&d.setAttribute("data-src"==e?"src":e,t.getAttribute(e))});let a=!(d.type="text/javascript");!d.src&&t.textContent&&(d.src=litespeed_inline2src(t.textContent),a=!0),t.after(d),t.remove(),a&&e()}function litespeed_inline2src(t){try{var d=urlCreator.createObjectURL(new Blob([t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1")],{type:"text/javascript"}))}catch(e){d="data:text/javascript;base64,"+btoa(t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1"))}return d}</script></body>
</html>

				
			
				
					// JavaScript Code (script.js)

// Function to display window dimensions
function displayWindowDimensions() {
  const width = window.innerWidth;
  const height = window.innerHeight;
  const resizeInfo = document.getElementById("resizeInfo");
  resizeInfo.textContent = `Window dimensions: ${width} x ${height}`;
}

// Add event listener for the resize event on the window object
window.addEventListener("resize", function(event) {
  console.log("Window has been resized.");

  // Call function to display window dimensions
  displayWindowDimensions();
});

// Call function initially to display window dimensions
displayWindowDimensions();

				
			

Explanation:

  • HTML Structure: We have a basic HTML structure with a <script> tag at the end of the body, which refers to an external JavaScript file named script.js. There’s also a <div> element with the id resizeInfo, which will display information about the window dimensions.
  • CSS Styling: Some CSS styling is added to position the resizeInfo <div> at the bottom right corner of the window.
  • JavaScript Function: We define a function displayWindowDimensions() to retrieve the current width and height of the window and display them in the resizeInfo <div>.
  • Window Resize Event Listener: We attach a resize event listener to the window object. When the window is resized, the event listener triggers, and it calls the displayWindowDimensions() function to update and display the new window dimensions.
  • Initial Call: We call the displayWindowDimensions() function initially to display the window dimensions when the page is loaded.

This example demonstrates how you can capture the resize event when the window is resized using JavaScript. It updates and displays the window dimensions dynamically as the window size changes.

Scroll Event

Here’s an example of the scroll event triggered when the user scrolls the page

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scroll Event Example</title><style>body {
      height: 2000px; /* Adding height to enable scrolling */
    }
    #scrollInfo {
      background-color: #f0f0f0;
      padding: 10px;
      position: fixed;
      bottom: 0;
      right: 0;
    }</style></head>
<body>
  <h1>Scroll the Page</h1>
  <p>Scroll the page to see the scroll event in action.</p>

  <div id="scrollInfo"></div> <script type="litespeed/javascript" data-src="script.js"></script> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script><script data-optimized="1" type="litespeed/javascript" data-src="https://diginode.in/wp-content/litespeed/js/96d0e6d4ba93134cbdab615e06eb2824.js?ver=a1a89"></script><script>const litespeed_ui_events=["mouseover","click","keydown","wheel","touchmove","touchstart"];var urlCreator=window.URL||window.webkitURL;function litespeed_load_delayed_js_force(){console.log("[LiteSpeed] Start Load JS Delayed"),litespeed_ui_events.forEach(e=>{window.removeEventListener(e,litespeed_load_delayed_js_force,{passive:!0})}),document.querySelectorAll("iframe[data-litespeed-src]").forEach(e=>{e.setAttribute("src",e.getAttribute("data-litespeed-src"))}),"loading"==document.readyState?window.addEventListener("DOMContentLoaded",litespeed_load_delayed_js):litespeed_load_delayed_js()}litespeed_ui_events.forEach(e=>{window.addEventListener(e,litespeed_load_delayed_js_force,{passive:!0})});async function litespeed_load_delayed_js(){let t=[];for(var d in document.querySelectorAll('script[type="litespeed/javascript"]').forEach(e=>{t.push(e)}),t)await new Promise(e=>litespeed_load_one(t[d],e));document.dispatchEvent(new Event("DOMContentLiteSpeedLoaded")),window.dispatchEvent(new Event("DOMContentLiteSpeedLoaded"))}function litespeed_load_one(t,e){console.log("[LiteSpeed] Load ",t);var d=document.createElement("script");d.addEventListener("load",e),d.addEventListener("error",e),t.getAttributeNames().forEach(e=>{"type"!=e&&d.setAttribute("data-src"==e?"src":e,t.getAttribute(e))});let a=!(d.type="text/javascript");!d.src&&t.textContent&&(d.src=litespeed_inline2src(t.textContent),a=!0),t.after(d),t.remove(),a&&e()}function litespeed_inline2src(t){try{var d=urlCreator.createObjectURL(new Blob([t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1")],{type:"text/javascript"}))}catch(e){d="data:text/javascript;base64,"+btoa(t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1"))}return d}</script></body>
</html>

				
			
				
					// JavaScript Code (script.js)

// Function to display scroll position
function displayScrollPosition() {
  const scrollInfo = document.getElementById("scrollInfo");
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  scrollInfo.textContent = `Scroll position: ${scrollTop}px`;
}

// Add event listener for the scroll event on the window object
window.addEventListener("scroll", function(event) {
  console.log("Page has been scrolled.");

  // Call function to display scroll position
  displayScrollPosition();
});

// Call function initially to display scroll position
displayScrollPosition();

				
			

Explanation

  • HTML Structure: We have a basic HTML structure with a <script> tag at the end of the body, which refers to an external JavaScript file named script.js. There’s also a <div> element with the id scrollInfo, which will display information about the scroll position.
  • CSS Styling: Some CSS styling is added to position the scrollInfo <div> at the bottom right corner of the window.
  • JavaScript Function: We define a function displayScrollPosition() to retrieve the current scroll position of the page and display it in the scrollInfo <div>.
  • Window Scroll Event Listener: We attach a scroll event listener to the window object. When the user scrolls the page, the event listener triggers, and it calls the displayScrollPosition() function to update and display the new scroll position.

This example demonstrates how you can capture the scroll event when the user scrolls the page using JavaScript. It updates and displays the scroll position dynamically as the user scrolls.

Unload Event

The unload event occurs when a user navigates away from a page, either by closing the browser tab/window or by navigating to another page. It can be used to perform cleanup tasks or execute certain actions before the user leaves the page. However, please note that the use of unload event is limited and some actions may not be reliable due to browser restrictions.

Here’s a basic example:

				
					

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Unload Event Example</title> <script src="script.js" defer></script> </head>
<body>
  <h1>Unload Event Example</h1>
  <p>Close this tab/window or navigate away to trigger the unload event.</p> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script><script data-optimized="1" type="litespeed/javascript" data-src="https://diginode.in/wp-content/litespeed/js/96d0e6d4ba93134cbdab615e06eb2824.js?ver=a1a89"></script><script>const litespeed_ui_events=["mouseover","click","keydown","wheel","touchmove","touchstart"];var urlCreator=window.URL||window.webkitURL;function litespeed_load_delayed_js_force(){console.log("[LiteSpeed] Start Load JS Delayed"),litespeed_ui_events.forEach(e=>{window.removeEventListener(e,litespeed_load_delayed_js_force,{passive:!0})}),document.querySelectorAll("iframe[data-litespeed-src]").forEach(e=>{e.setAttribute("src",e.getAttribute("data-litespeed-src"))}),"loading"==document.readyState?window.addEventListener("DOMContentLoaded",litespeed_load_delayed_js):litespeed_load_delayed_js()}litespeed_ui_events.forEach(e=>{window.addEventListener(e,litespeed_load_delayed_js_force,{passive:!0})});async function litespeed_load_delayed_js(){let t=[];for(var d in document.querySelectorAll('script[type="litespeed/javascript"]').forEach(e=>{t.push(e)}),t)await new Promise(e=>litespeed_load_one(t[d],e));document.dispatchEvent(new Event("DOMContentLiteSpeedLoaded")),window.dispatchEvent(new Event("DOMContentLiteSpeedLoaded"))}function litespeed_load_one(t,e){console.log("[LiteSpeed] Load ",t);var d=document.createElement("script");d.addEventListener("load",e),d.addEventListener("error",e),t.getAttributeNames().forEach(e=>{"type"!=e&&d.setAttribute("data-src"==e?"src":e,t.getAttribute(e))});let a=!(d.type="text/javascript");!d.src&&t.textContent&&(d.src=litespeed_inline2src(t.textContent),a=!0),t.after(d),t.remove(),a&&e()}function litespeed_inline2src(t){try{var d=urlCreator.createObjectURL(new Blob([t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1")],{type:"text/javascript"}))}catch(e){d="data:text/javascript;base64,"+btoa(t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1"))}return d}</script></body>
</html>


				
			
				
					// JavaScript Code (script.js)

// Add event listener for the unload event on the window object
window.addEventListener("unload", function(event) {
  // Perform cleanup tasks or execute actions before the user leaves the page
  console.log("Page is being unloaded. Perform cleanup tasks here.");
});

				
			

Explanation:

  • HTML Structure: We have a basic HTML structure with a <script> tag at the end of the <head> section, which refers to an external JavaScript file named script.js.
  • JavaScript Code: We attach an unload event listener to the window object. When the user navigates away from the page (by closing the tab/window or navigating to another page), the unload event is triggered, and the event listener executes the associated function.
  • Event Handling: Inside the event listener, you can perform cleanup tasks or execute actions that need to be completed before the user leaves the page. In this example, we simply log a message to the console indicating that the page is being unloaded.

Please note that the unload event may not be supported in all browsers, and some actions performed within this event may not work consistently due to browser restrictions. Additionally, heavy operations or network requests initiated within the unload event may not complete before the page is unloaded. Therefore, it’s generally recommended to use alternative methods for tasks that require reliability and consistency across different browsers and environments.

Custom Event

Event TypeDescriptionExample Usage
(User-defined)You can define your own custom events to signal specific actions within your applicationTriggering custom functionality between components

Custom Event

To provide an example of a custom event, let’s imagine a scenario where we want to notify components in our web application when a user successfully logs in. We can define a custom event called “loginSuccess” and dispatch it whenever a successful login occurs. Other parts of the application that need to react to this event can listen for it and perform appropriate actions.

 
				
					
<form id="loginForm">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">
  <br>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password">
  <br>
  <button type="submit">Login</button>
</form>

				
			
				
					// JavaScript (Login Logic)
const loginForm = document.getElementById("loginForm");

loginForm.addEventListener("submit", function(event) {
  event.preventDefault(); // Prevent form submission

  // Simulate login logic (check username and password)
  const username = document.getElementById("username").value;
  const password = document.getElementById("password").value;

  // Assuming authentication is successful
  if (username === "user" && password === "password") {
    // Dispatch custom event for login success
    const loginSuccessEvent = new Event("loginSuccess");
    document.dispatchEvent(loginSuccessEvent);
    console.log("Login successful!");
  } else {
    console.log("Login failed. Please check your credentials.");
  }
});

// JavaScript (Other Components Listening for Login Success)
document.addEventListener("loginSuccess", function(event) {
  // Perform actions when login is successful
  console.log("Welcome! You are now logged in.");
  // For example, update UI, fetch user data, etc.
});

				
			

Explanation:

  1. Login Form: We have a basic login form with input fields for username and password, and a submit button.

  2. Login Logic: When the form is submitted, we prevent the default form submission behavior using event.preventDefault(). We simulate a login process by checking the entered username and password. If the credentials are correct, we dispatch a custom event named “loginSuccess” using document.dispatchEvent().
    1. Other Components Listening: Elsewhere in the application, components can listen for the “loginSuccess” event using document.addEventListener(). When the event is received, these components can perform actions such as updating the UI to reflect the user’s logged-in state or fetching additional data.

    This example demonstrates how custom events can be used to create a communication mechanism between different parts of a web application, allowing for decoupled and modular code.

JavaScript's event handling allows developers to create interactive and responsive web experiences by capturing and responding to user actions and browser events. Key concepts include event types, propagation (bubbling and capturing), and the flexibility of `addEventListener` for attaching multiple handlers. Advanced techniques like event delegation optimize performance, while custom events enable decoupled communication between components. Events like keyboard, form validation, and touch interactions further enhance functionality across devices. Mastering event handling is essential for building dynamic, user-friendly applications.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India