Category: Events

  • Custom Events

    Custom Events

    The custom events in JavaScript define and handle custom interactions or signals within an application. They establish a communication mechanism between various sections of your code: one part can notify others about specific occurrences or changes; thus enhancing the functionality of your program.

    Typically, users utilize custom events in conjunction with the Event and CustomEvent interfaces. The following provides a detailed breakdown of their functionality:

    ConceptDescription
    Custom EventThe CustomEvent constructor in JavaScript facilitates communication between various parts of an application by defining a user-specific event. Such custom events manifest as instances of this constructor.
    CustomEvent ConstructorThe built-in JavaScript constructor creates custom events, utilizing two parameters: the event type, a string, and a discretionary configuration object; for instance, an optional detail property can be used to provide supplementary data.
    dispatchEvent MethodA method available on DOM elements that dispatches a custom event. It triggers the execution of all listeners for that event type on the specified element.
    addEventListener MethodA method available on DOM elements to attach an event listener function to an event type. The listener function is executed when the specified event is dispatched on the element.
    Event TypesStrings that identify the type of event. Custom events can have any user-defined string as their type.
    Event HandlingListening for and responding to events is an active process. It primarily involves the creation of listeners for specific event types in custom contexts, and subsequently defining precise actions that will occur when these events take place.
    Pub/Sub PatternIn this design pattern, system components communicate with each other indirectly and without direct references. By utilizing custom events, one can implement a publish/subscribe pattern that enables various application sections to subscribe to specific events and react accordingly.
    detail PropertyAn optional property in the configuration object when creating a custom event. It allows you to pass additional data (as an object) along with the event.

    Example: Basic Custom Event

    In this example, we initiate a custom event named ‘myCustomEvent’ and render an associated button. Using the addEventListener method, we track events triggered by this button. Upon clicking the button, our action dispatches the custom event; subsequently alerting a message “Custom event triggered!”

    <!DOCTYPE html><html><body><button id="triggerBtn">Trigger Event</button><script>// Creates the new custom event.const customEvent =newEvent('myCustomEvent');// Adds an event listener to the button.
    		document.getElementById('triggerBtn').addEventListener('click',function(){// Dispatches custom event on button click.
    			document.dispatchEvent(customEvent);});// Add listener for the custom event.
    		document.addEventListener('myCustomEvent',function(){alert('Custom event triggered!');});</script></body></html>

    Example: Custom Event with Data

    In this example we will make use of the CustomEvent which is an interface and extends the primary Event. The detail property will be demonstrated here which allows us to set additional data. The custom event name will be ‘myCustomEventWithData’ and it will have a message associated to it. This custom event will be getting dispatched upon the click of a button. When this button is clicked, this event will be triggered and the message set will be alerted on screen.

    <!DOCTYPE html><html><body><button id="triggerBtn">Trigger Custom Event</button><script>const eventData ={ message:'Hello from custom event!'};const customEvent =newCustomEvent('myCustomEventWithData',{ detail: eventData });
    		document.getElementById('triggerBtn').addEventListener('click',function(){       
    			document.dispatchEvent(customEvent);});
    		document.addEventListener('myCustomEventWithData',function(event){alert('Custom event triggered with data: '+ event.detail.message);});</script></body></html>

    Example: Condition-based Event Dispatching

    This example illuminates a scenario: event dispatching critically hinges on a variable (v), being conditionally based. It underscores your application’s dynamic use of custom events, dependent upon specific conditions. The case at hand involves the dispatching either ‘TutorialEvent’ or ‘TutorialEvent2’ determined by the value of v; correspondingly, an event listener reacts accordingly to this choice.

    <!DOCTYPE html><html><body><script>var v='tutorialspoint';const event =newEvent("TutorialEvent");const event2 =newEvent("TutorialEvent2");
    	 
    		document.addEventListener('TutorialEvent',()=>{alert("Welcome to Tutorialspoint Event")});
    		document.addEventListener('TutorialEvent2',()=>{alert("Welcome to Event 2")});if(v =='tutorialspoint'){
    			document.dispatchEvent(event);}else{
    			document.dispatchEvent(event2);}</script></body></html>

    To summarize the steps for creating custom events, we first create an event or Custom event, add the listener using the addEventListener (preferably) and then we trigger or dispatch the event using the. dispatchEvent method.

  • Event Capturing

    Event Capturing

    Event capturing in JavaScript is the initial phase in the event propagation model where the event travels from the root of the document tree down to the target element. During this phase, the browser captures the event on the ancestors of the target element before reaching the target itself.

    Event capturing and event bubbling are two phases in the JavaScript event propagation model. In event capturing, the browser captures and triggers events starting from the root of the document hierarchy and moving down to the target element. On the other hand, event bubbling occurs after the event reaches the target element and then bubbles up from the target to the root.

    Capturing is useful for handling events at higher-level ancestors, while bubbling is the default behaviour where events propagate from the target back up the hierarchy. Understanding both phases is crucial for effective event handling and manipulation of the event flow.

    Let us see some important aspects of event capturing.

    AspectDescription
    PhaseEvent capturing is the initial phase in the event propagation model.
    DirectionCapturing occurs in the reverse order of the element hierarchy, from the root of the document tree down to the target element.
    Use CaseUseful when you want to intercept and handle events at a higher-level ancestor before they reach the target element or trigger any bubbling phase handlers.
    RegistrationRegister event listeners for the capturing phase using the third parameter of addEventListener (e.g., element.addEventListener(‘click’, myFunction, true);).
    PropagationAutomatic propagation that precedes the target and bubbling phases. The event flows down the hierarchy, triggering capturing phase handlers on each ancestor.
    Preventing DefaultUse event.preventDefault() during the capturing phase to prevent the default behavior of the event before it reaches the target.
    Stopping PropagationUse event.stopPropagation() in the capturing phase to stop further propagation of the event, preventing it from reaching the target or triggering bubbling phase handlers.

    Example: Basic Event Capturing

    In this example, we have a container div (container) and a button (myButton) inside it. Two capturing phase event listeners are added using addEventListener with the true parameter to enable capturing. When you click the button, both capturing phase log messages (Container clicked and Button clicked) will be displayed. This illustrates the capturing phase as the event travels from the document root down to the target element.

    <!DOCTYPE html><html><body><div id="container"><button id="myButton">Click me!</button></div><div id ="output"></div><script>const output = document.getElementById('output');
    		document.getElementById('container').addEventListener('click',function(event){
    			output.innerHTML +='Capturing phase - Container clicked'+"<br>";},true);
    
    		document.getElementById('myButton').addEventListener('click',function(event){
    			output.innerHTML +='Capturing phase - Button clicked'+"<br>";},true);</script></body></html>

    Example: Preventing Default Behaviour

    In this example, we have a hyperlink (<a>) with an id of “link”. The capturing phase event listener is attached to the link during the capturing phase. When you click the link, the capturing phase log message (Link clicked) will be displayed, and the default behaviour (navigating to a new page) is prevented using event.preventDefault().

    If the. preventDefault() was not used, it would have navigated the page to https://www.tutorialspoint.com.

    <!DOCTYPE html><html><body><a href="https://www.tutorialspoint.com" id="link">Click me to prevent default</a><script>
    		document.getElementById('link').addEventListener('click',function(event){alert('Capturing phase - Link clicked');
    			event.preventDefault();// Prevent the default behavior (e.g., navigating to a new page)},true);</script></body></html>

    Example: Capturing and Stopping Propagation

    In this example, the parent div’s capturing phase event listener actively halts propagation through the use of ‘event.stopPropagation()’. Only upon clicking the button will you see a log message during capture phase (“Parent clicked”) being displayed; however, it does not trigger any further action within child elements’ capturing phases. This indeed showcases an effective method to arrest additional propagation in this particular instance.

    <!DOCTYPE html><html><body><div id="parent"><button id="child">Click me!</button></div><div id ="output"></div><script>const output = document.getElementById('output');
    document.getElementById('parent').addEventListener('click',function(event){
    output.innerHTML +='Capturing phase - Parent clicked'+"<br>";// Stop further propagation to the child element
    event.stopPropagation();},true);
    document.getElementById('child').addEventListener('click',function(event){
    output.innerHTML +='Capturing phase - Child clicked'+"<br>";},true);</script></body></html>
  • Event Bubbling

    Event Bubbling

    Event bubbling is a concept in JavaScript that refers to the order in which events are handled as they propagate through the DOM (Document Object Model) hierarchy. When an event occurs on a particular element, such as a click or a keypress, it can trigger handlers not only on that specific element but also on its ancestors in the DOM tree.

    Event Bubbling Steps

    Here’s a step-by-step explanation of event bubbling −

    Event Triggering

    • An event is triggered on a specific DOM element, like a button being clicked or a key being pressed.
    • This is the starting point of the event propagation.

    Capturing Phase (optional)

    • The event can optionally go through the capturing phase. This phase starts from the root of the DOM tree and moves towards the target element.
    • During this phase, event handlers registered with the addEventListener method using the third parameter true will be executed.

    Target Phase

    • The event reaches the target element, the one on which the event originally occurred.

    Bubbling Phase

    • After the target phase, the event starts to bubble up from the target element towards the root of the DOM tree.
    • During this phase, event handlers registered without the third parameter or with the third parameter set to false will be executed.

    Event Bubbling using 2 Nested DIVs

    In this example of nested <div> elements, event bubbling is evident as the click event on the child <div> propagates up through the DOM hierarchy to trigger the click event listener on the parent <div>. Despite being clicked on the child, both the child and parent event listeners respond to the click event sequentially.

    This behaviour showcases the default event bubbling mechanism in the DOM, where events traverse from the target element up to its ancestors, allowing multiple elements to respond to the same event. In the console, upon clicking the child <div>, the log messages for both the child and parent event listeners are displayed, illustrating the event bubbling process.

    <!DOCTYPE html><html lang="en"><head><style>.parent {
    			width:600px;
    			height:200px;
    			background-color: #eee;
    			position: relative;
    			cursor: pointer;}.child {
    			width:400px;
    			height:100px;
    			background-color: #66c2ff;
    			position: absolute;
    			top:50px;
    			left:50px;}
    		#message {
    			margin-top:10px;
    			font-weight: bold;}</style></head><body><h2>Nested Divs</h2><div class="parent" id="parentDiv"><div class="child" id="childDiv">Click me!</div></div><div id="message"></div><script>let messageElement = document.getElementById('message');
    
    		document.getElementById('parentDiv').addEventListener('click',function(){
    			messageElement.innerHTML+='Parent div clicked<br>';});
    
    		document.getElementById('childDiv').addEventListener('click',function(){
    			messageElement.innerHTML+='Child div clicked<br>';});</script></body></html>

    The grey box is the parent div and blue box is the child div.

    Event Bubbling using 3 Nested Levels

    In this example with three nested levels of <div> elements, event bubbling is demonstrated as a click on the innermost Level 3 <div> triggers successive click event listeners on the parent Level 2 and Level 1 <div> elements. Styled with distinctive background colours, each level visually represents its hierarchy.

    Upon clicking the Level 3 <div>, the event propagates up, invoking event listeners for higher-level elements. Console logs reveal messages indicating the clicked level and its background colour, showcasing the streamlined event bubbling mechanism for handling nested structures in the DOM.

    <!DOCTYPE html><html><head><style>.level1 {
    			background-color: #ff9999;
    			padding:20px;
    			text-align: center;
    			max-width:80%;
    			cursor: pointer;}.level2 {
    			background-color: #99ff99;
    			padding:15px;}.level3 {
    			background-color: #9999ff;
    			padding:10px;
    			cursor: pointer;}
    		#message {
    			margin-top:10px;
    			font-weight: lighter;
    			border:1px solid #ddd;
    			padding:10px;
    			max-width:80%;
    			background-color: #f9f9f9;
    			border-radius:5px;
    			font-family:'Arial', sans-serif;
    			font-size:14px;
    			color: #333;}</style></head><body><div class="level1" id="div1">
    		Level 1<div class="level2" id="div2">
    			Level 2<div class="level3" id="div3">
    
    			Level 3(Click me!)&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div id="message"&gt;&lt;/div&gt;&lt;script&gt;const messageElement = document.getElementById("message");
    document.getElementById('div1').addEventListener("click",function(event){ messageElement.innerHTML +="Clicked on Level 1, Background Color:"+getComputedStyle(event.target).backgroundColor +"<br>";}); document.getElementById('div2').addEventListener("click",function(event){ messageElement.innerHTML +="Clicked on Level 2, Background Color:"+getComputedStyle(event.target).backgroundColor +"<br>";}); document.getElementById('div3').addEventListener('click',function(event){ messageElement.innerHTML +="Clicked on Level 3, Background Color:"+getComputedStyle(event.target).backgroundColor +"<br>";});</script></body></html>
  • Event Delegation

    Event delegation in JavaScript is a technique that allows us to attach a single event listener to a parent element, and then use the event object to determine which child element triggered the event. This way, we can handle multiple events with a single event listener, and avoid adding too many event listeners to the DOM.

    Steps of Event Delegation

    1. Attach a Listener to a Common Ancestor

    Attach a single event listener to a parent element, encapsulating the elements you wish to monitor; this is in lieu of attaching individual event listeners for each element. Use methods such as addEventListener for efficient implementation.

    2. Check the Target Element

    Inspect the event.target property within the event handler to pinpoint the specific element that triggered it in its common ancestor. Common checks involve scrutinizing tagName, classList, or other target element properties.

    3. Perform the Desired Action

    Based on the identified target element and any specified criteria, execute the desired action or functionality. This could involve modifying content, handling a button click, or performing any custom logic associated with the event.

    Event Delegation Examples

    Example: List Item Clicks

    In this example, we employ event delegation to adeptly manage clicks on a dynamically changing list of tutorials. The <ul> element serving as the shared ancestor for all list items has one solitary event listener attached to it.

    Upon clicking a tutorial, an <li> identifies itself as the target via our skilfully crafted event handler; consequently, enabling logging of that particular tutorial’s content in the console. This demonstrates the streamlined and scalable approach of event delegation in managing dynamic lists.

    <!DOCTYPE html><html><head><style>
    
      ul {list-style-type: none; padding:0;}
      li {margin:5px; 
         padding:10px;
         border:1px solid #ccc;
         cursor: pointer; 
         max-width:30%;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;ul id="myList"&gt;&lt;li&gt;Tutorial 1&lt;/li&gt;&lt;li&gt;Tutorial 2&lt;/li&gt;&lt;li&gt;Tutorial 3&lt;/li&gt;&lt;li&gt;Tutorial 4&lt;/li&gt;&lt;li&gt;Tutorial 5&lt;/li&gt;&lt;/ul&gt;&lt;div id ="output"&gt;&lt;/div&gt;&lt;script&gt;const output = document.getElementById("output");const myList = document.getElementById("myList")
      myList.addEventListener("click",function(event){if(event.target.tagName ==="LI"){
            output.innerHTML +="Tutorial clicked: "+ 
    event.target.textContent +"<br>";}});</script></body></html>

    Example: Form Control Changes

    Employing event delegation here allows for the monitoring and logging of changes in form control values: the <form> element acts as a common ancestor, while an input event listener captures alterations within input fields. The script confirms by examining the target element within its handler, that events are indeed related to an <input>. The message, consequently, logs the modified input’s name and new value: this action not only showcases event delegation’s adaptability but also its efficiency in managing dynamic form interactions.

    <!DOCTYPE html><html><body><form id="myForm"><input type="text" name="username" placeholder="Username"><input type="password" name="password" placeholder="Password"><button type="button">Submit</button></form><div id="message"></div><script>const messageElement = document.getElementById("message");const myForm = document.getElementById("myForm")
    
      myForm.addEventListener("input",function(event){if(event.target.nodeName ==="INPUT"){
            messageElement.innerHTML +="Input changed: "+ event.target.name +" - New value: "+ event.target.value+'&lt;br&gt;';}});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Event delegation is valuable in scenarios where a single event listener can efficiently manage interactions for multiple elements, reducing redundancy and improving performance. Common use cases include handling dynamic lists, form interactions, table actions, accordion or tabbed interfaces, tree structures, dropdown menus, multi-step wizards, carousels, and various interactive UI components. It simplifies code structure, ensures consistency, and adapts well to dynamic content changes, making it a versatile technique in web development.

  • Window/Document Events

    JavaScript window events are actions that occur when the user does something affecting the entire browser window, like loading, resizing, closing, or moving the window. The most common window event is simply loading the window by opening a particular web page. This event is handled by the onload event handler.

    Developers can use JavaScript to create dynamic, interactive web pages that respond to user actions. The interactivity depends on two core aspects: window events and document events. Operating at the browser’s panoramic level, window events bestow control over the overall state of the browser window; alternatively, document events interact with the HTML document, empowering developers to react specifically towards elements or actions within a page

    Window Events

    At the browser level, window events happen and hold association with the window object; this global object represents the web browser’s window. Frequently employed to oversee the overall state of a browser window or manage global interactions are these types of events.

    Event NameDescription
    loadTriggered when the entire web page, including all its resources, has finished loading.
    unloadFired when the user is leaving the page or closing the browser window or tab.
    resizeActivated when the size of the browser window is changed.
    scrollFired when the user scrolls the page.

    Example: Demonstrating Window Events

    In this example, a script actively listens for the ‘load,’ ‘resize,’ and ‘scroll’ events on the window; it includes an initial page load alert to inform users that loading is complete. Should they subsequently resize their window, an alert will trigger thereby displaying the new size of their updated viewport. Moreover, when the user scrolls on the page, an alert is triggered to indicate their action.

    <!DOCTYPE html><html><head><title>Window Events Example</title><style>
    
      body {
         height:2000px;/* Adding some content just to enable scrolling */}
      #resizeInfo {
         position: fixed;
         top:10px;
         left:10px;
         background-color: #fff;
         padding:10px;
         border:1px solid #ccc;}&lt;/style&gt;&lt;script&gt;
      window.addEventListener('load',function(){var initialSizeInfo ='Initial window size: '+ window.innerWidth +' x '+ window.innerHeight;
         document.getElementById('resizeInfo').innerText = initialSizeInfo;alert('The page has finished loading!');});
      window.addEventListener('resize',function(){var newSizeInfo ='New window size: '+ window.innerWidth +' x '+ window.innerHeight;
         document.getElementById('resizeInfo').innerText = newSizeInfo;alert("Page has been resized");});
      window.addEventListener('scroll',function(){alert('You have scrolled on this page.');},{once:true});&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;div id="resizeInfo"&gt;Initial window size: ${window.innerWidth} x ${window.innerHeight}&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Document Events

    Document events on the other hand occur at the level of the HTML document within the window and are associated with the document object which represents the HTML document thereby providing an interface to interact with the content of the page.

    Event NameDescription
    DOMContentLoadedTriggered when the HTML document has been completely loaded and parsed, without waiting for external resources like images.
    clickFired when the user clicks on an element.
    submitTriggered when a form is submitted.
    keydown/keyup/keypressThese events are triggered when a key is pressed, released, or both, respectively.
    changeFired when the value of an input element changes, such as with text inputs or dropdowns.

    Example: Demonstrating Document Events

    In this example, we've included a script that listens for the 'DOMContentLoaded,' 'click,' 'submit,' and 'keydown' events on the document. Upon the 'DOMContentLoaded' event, it logs to the console that the DOM content has been fully loaded. Subsequently, clicking an element triggers an alert displaying the tag name of the clicked element. Submitting a form also alerts that the form has been submitted. Furthermore, pressing a key like entering the username with characters, alerts every keypress to the screen.

    <!DOCTYPE html><html><head><title>Document Events Example</title><script>
    
      document.addEventListener('DOMContentLoaded',function(){alert('DOM content has been fully loaded!');});
      document.addEventListener('click',function(event){alert('Element clicked! Tag Name: '+ event.target.tagName);},{once:true});
      document.addEventListener('submit',function(){alert('Form submitted!');});
      document.addEventListener('keydown',function(event){alert('Key pressed: '+ event.key);},{once:true});&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form&gt;&lt;label for="username"&gt;Username:&lt;/label&gt;&lt;input type="text" id="username" name="username"&gt;&lt;button type="submit"&gt;Submit&lt;/button&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Form Events

    Form Events

    The form events in JavaScript are events that are associated with HTML forms. These events are triggered by user actions when interacting with form elements like text fields, buttons, checkboxes, etc. Form events allow you to execute JavaScript code in response to these actions, enabling you to validate form data, perform actions on form submission or reset, and enhance the user experience.

    JavaScript form events are hooked onto the elements in the Document Object Model also known as DOM where by default the bubbling propagation is used i.e. from bottom (children) to top(parent).

    List of Common Form Events

    Here are some common form events:

    Form EventDescription
    onsubmitTriggered when a form is submitted. It’s often used for form validation before data is sent to the server.
    onresetTriggered when the form is reset, allowing you to perform actions when the user resets the form.
    onchangeTriggered when the value of a form element (input, select, textarea) changes. Commonly used for user input validation or dynamic updates.
    oninputTriggered immediately when the value of an input element changes, allowing for real-time handling of user input.
    onfocusTriggered when an element receives focus, such as when a user clicks or tabs into an input field. Useful for providing feedback or enhancing the user experience.
    onblurTriggered when an element loses focus, such as when a user clicks outside an input field or tabs away. Useful for validation or updates triggered by loss of focus.

    Examples

    Example: The onchange Event

    The provided instance below illustrates the functionality of the onchange event. This event activates upon a user’s alteration in dropdown (<select>) option selection. The function, handleChange, dynamically modifies an <h2> element to display the newly selected country; thus offering immediate feedback as user preferences evolve.

    <!DOCTYPE html><html><body><label for="country">Select a country:</label><select id="country" onchange="handleChange()"><option value="USA">USA</option><option value="Canada">Canada</option><option value="UK">UK</option><option value="India">India</option></select><p id="txt"></p><script>functionhandleChange(){// Perform actions when the dropdown selection changesvar selectedCountry = document.getElementById('country').value;
    
         document.getElementById("txt").textContent="Selected country: "+selectedCountry;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: The onsubmit Event

    The following example highlights the onsubmit event's functionality upon form submission. The form features a username field and password field; both must be filled for successful validation when invoking the validateForm function. Upon passing this validation, submitting the form will trigger display of a confirmation message.

    <!DOCTYPE html><html><body><form onsubmit="return validateForm()"><label for="username">Username:</label><input type="text" id="username" name="username" required><label for="password">Password:</label><input type="password" id="password" name="password" required><br/><input type="submit" value="Submit"></form><script>functionvalidateForm(){var username = document.getElementById('username').value;var password = document.getElementById('password').value;// Perform validationif(username ===""|| password ===""){alert("Please fill in all fields");returnfalse;// Prevent form submission}alert("Form submitted! Username is:"+username+",Password is:"+password);returntrue;// Allow form submission}</script></body></html>

    Example: The onreset event

    In this demonstration, we observe the onreset event in action: it triggers upon the user's click of the "Reset" button within a form. The resetForm function once invoked, clears the form content filled by user and then displays an alert to confirm successful reset of said form.

    <!DOCTYPE html><html><body><form onreset="resetForm()"><label for="email">Email:</label><input type="email" id="email" name="email" required><input type="reset" value="Reset"></form><script>functionresetForm(){// Perform actions when the form is resetalert("Form has been reset!");}</script></body></html>

    Example: The oninput Event

    This example illustrates the oninput event: as the user types into the search input field a real-time action, indeed! The handleInput function triggers; it logs each current search input directly to screen.

    <!DOCTYPE html><html><body><label for="search">Search:</label><input type="text" id="search" oninput="handleInput()"><div id="message" style=" margin-top: 10px; font-weight: lighter;border: 1px solid #ddd;padding: 10px; background-color: #f9f9f9; border-radius: 5px; font-family: 'Arial', sans-serif; font-size: 14px; color: #333; width: 30%;"></div><script>var messageElement = document.getElementById('message');functionhandleInput(){// Perform actions as the user typesvar searchInput = document.getElementById('search').value;
    
         messageElement.innerHTML+="Search input: "+ searchInput+'&lt;br&gt;';}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: onfocus and onblur Events

    The onfocus and onblur events merge in this example. The user's focus on the input field triggers a call to the handleFocus function, which then logs a message into the console. In contrast, when clicks outside of or tabs away from said input field this action triggers execution of another function called handleBlur that subsequently records an alternative message within that same console log.

    <!DOCTYPE html><html><body><label for="name">Name:</label><input type="text" id="name" onfocus="handleFocus()" onblur="handleBlur()"><p id="output"></p><script>const output = document.getElementById('output');functionhandleFocus(){// Perform actions when the input gets focus
    
         output.innerHTML +="Input has focus"+"&lt;br&gt;";}functionhandleBlur(){// Perform actions when the input loses focus
         output.innerHTML +="Input lost focus"+"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Keyboard Events

    The keyboard events in JavaScript provide a way to interact with a web page or application based on the user’s keyboard input. These events allow developers to capture and respond to various keyboard actions, such as key presses, key releases, and character inputs. The primary keyboard events in JavaScript include keydown, keypress, and keyup.

    Common Keyboard Events

    • Keydown Event − When a key on the keyboard is pressed down, it triggers the keydown event. This event equips developers with information about the specific key that was pressed: this includes its code and an indicator of whether certain modifier keys such as Shift, Ctrl, or Alt were also depressed.
    • Keypress Event − The keypress event triggers when a user types an actual character. Non-character keys, such as Shift or Ctrl, do not activate this event. Developers frequently utilize it to capture user input for form fields or create interactive typing features.
    • Keyup Event − Upon the release of a previously pressed key, the system initiates the firing of a keyup event; this particular event proves beneficial in tracking specific keys’ releases and subsequently implementing actions, thereby creating an interactive user experience.

    Keyboard Event Properties

    For keyboard events in JavaScript, several properties are commonly used to gather information about the key pressed. Here are some key properties specifically relevant to keyboard events −

    PropertyDescription
    event.keyString representing the key value of the pressed key.
    event.codeString representing the physical key on the keyboard.
    event.locationInteger indicating the location of the key on the keyboard.
    event.ctrlKeyBoolean indicating whether the Ctrl key was held down.
    event.shiftKeyBoolean indicating whether the Shift key was held down.
    event.altKeyBoolean indicating whether the Alt key was held down.
    event.metaKeyBoolean indicating whether the Meta (Command) key was held down.
    event.repeatBoolean indicating whether the key event is a repeat event.
    event.isComposingBoolean indicating whether the event is part of a composition of multiple keystrokes.
    event.whichDeprecated property; previously used to identify the numeric key code.
    event.getModifierState(keyArg)Method that returns a boolean indicating whether the modifier key is pressed.

    Example: Keydown Event

    This example illustrates the application of JavaScript’s keydown event. The event listener seizes the keydown event upon pressing any key, displaying in an HTML element identified as “output” – its corresponding key (an event property).

    <!DOCTYPE html><html><body><h3>Press any key</h3><script>
    
      document.addEventListener('keydown',function(event){
         document.getElementById('output').innerHTML ="Key pressed: "+ event.key;});&lt;/script&gt;&lt;div id="output"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Keypress Event

    In this example, the keypress event is utilized to capture a typed character. When a character is typed, the event listener triggers, and the character is displayed in the HTML element with the id "output".

    <!DOCTYPE html><html><body><h3>Type a character</h3><div id="output"></div><script>
    
      document.addEventListener('keypress',function(event){
         document.getElementById('output').innerHTML ="Character pressed: "+ event.key;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Keyup Event

    The keyup event is showcased in this example. It captures the event when a key is released after being pressed. The released key is then displayed on screen.

    <!DOCTYPE html><html><body><h3>Press and Release a key</h3><div id="output"></div><script>
    
      document.addEventListener('keyup',function(event){
         document.getElementById('output').innerHTML ="Key released: "+ event.key;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    There is a difference between keydown and keypress. keydown is triggered when any key is pressed down, providing information about the pressed key, including modifiers. keypress is triggered specifically when a character key is pressed, providing information about the typed character without details on modifiers. Keydown fires continuously as long as the key is held down.

    In all the above examples, we have used the addEventListener but these events can be listened to without this function as well. This is because of you can assign event handlers directly to specific properties. However, keep in mind that using addEventListener is generally considered a better practice because it allows you to attach multiple event handlers to the same event, and it separates JavaScript logic from the HTML structure.

    Example: Without using addEventListener method

    In this example, we have an input box. When it detects a keydown event (onkeydown), the handleKeyDown function is called and when it detects a keyup event (onkeyup) it calls the handleKeyUp function. Both the functions print appropriate messages to the screen.

    <!DOCTYPE html><html><body><div>Enter some text:<input onkeydown="handleKeyDown(event)" onkeyup="handleKeyUp(event)"></div><div id="output"></div><script>functionhandleKeyDown(event){
    
         document.getElementById('output').innerHTML+="Key pressed: "+ event.key+'&lt;br&gt;Key code: '+ event.keyCode+'&lt;br&gt;';}functionhandleKeyUp(event){
         document.getElementById('output').innerHTML+="Key released: ' + event.key+'&lt;br&gt;&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Mouse Events

    JavaScript mouse events allow users to control and interact with web pages using their mouse. These events trigger specific functions or actions in response to user clicks, scrolls, drags, and other mouse movements.

    To handle mouse events in JavaScript, you can use the addEventListener() method. The addEventListener() method takes two arguments: the event type and the event handler function. The event type is the name of the event that you want to handle, and the event handler function is the function that will be called when the event occurs.

    In web development, JavaScript provides a powerful mechanism to respond to user interactions with the mouse through a set of events. These events enable developers to create dynamic and interactive web applications by capturing and handling various mouse-related actions.

    Common Mouse Events

    Following are the most common JavaScript mouse events:

    Mouse EventDescription
    ClickWhen an element experiences the press of a mouse button, it triggers the click event.
    Double ClickThe dblclick event fires upon the rapid double-clicking of a mouse button.
    Mouse Down and Mouse UpThe initiation of a mouse click triggers the ‘mousedown’ event, while the completion of that click causes the ‘mouseup’ event to occur.
    Mouse MoveWhen the mouse pointer moves over an element, it triggers the ‘mousemove’ event; this event supplies developers with positional information about the mouse. This data empowers them to devise responsive interfaces that are rooted in dynamic mouse movements.
    Context MenuWhen the user attempts to open the context menu, typically by right-clicking, they trigger the contextmenu event. This event allows developers to customize or inhibit default behaviour of the context menu.
    WheelWhen the mouse wheel rotates, it fires the ‘wheel event’; this particular event commonly manifests in implementing features, notably zooming or scrolling.
    Drag and DropEvents like dragstart, dragend, dragover, dragenter, dragleave, and drop are associated with drag-and-drop functionality. They allow developers to create interactive interfaces for dragging elements within a web page.

    Example : Click Event

    In this example we demonstrate the click event. When the button is clicked, it prints an appropriate message to the console message i.e. Clicked!. This event is often used while submitting forms.

    <!DOCTYPE html><html><head><title>Click Event Example</title></head><body><button id="clickButton">Click me!</button><p id ="output"></p><script>const clickButton = document.getElementById('clickButton');const outputDiv = document.getElementById("output");
    
      clickButton.addEventListener('click',function(event){
         outputDiv.innerHTML +='Clicked!'+JSON.stringify(event)+"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Double Click Event

    The dblclick event operates in this example, triggering upon a double-click of the designated button. We attach the event listener to an element with "doubleClickButton" as its id. A user's double-click on the button prompts a function that logs a console message, confirming their interaction with it.

    <!DOCTYPE html><html><head><title>Double Click Event Example</title></head><body><button id="doubleClickButton">Double-click me!</button><p id ="output"></p><script>const doubleClickButton = document.getElementById('doubleClickButton');const outputDiv = document.getElementById("output");
    
      doubleClickButton.addEventListener('dblclick',function(event){
         outputDiv.innerHTML +='Double-clicked!'+JSON.stringify(event)+"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Mouse Down and Mouse Up Events

    The use of the mousedown and mouseup events is exemplified in this scenario: both events apply to a <div> element identified as "mouseUpDownDiv." Two distinct event listeners are established; one responds to the down action of the mouse button, while another reacts upon release or up motion of said button. Upon pressing over the designated div (mousedown), a message indicating that the user has depressed their mouse button appears within your console log. When the user releases the mouse button (mouseup), we also log another message to indicate that the mouse button is up.

    <!DOCTYPE html><html><head><title>Mouse Down and Mouse Up Events Example</title></head><body><div id="mouseUpDownDiv" 
       style="width: 600px; height: 100px; background-color: lightblue;">
       Please perform mouse down and up event any where inthisDIV.</div><p id ="output"></p><script>const mouseUpDownDiv = document.getElementById('mouseUpDownDiv');const outputDiv = document.getElementById("output");
    
      mouseUpDownDiv.addEventListener('mousedown',function(event){
         outputDiv.innerHTML +='Mouse button down!'+JSON.stringify(event)+"&lt;br&gt;";});
      mouseUpDownDiv.addEventListener('mouseup',function(event){
         outputDiv.innerHTML +='Mouse button up!'+JSON.stringify(event)+"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Mouse Move Event

    In this instance, we employ the mousemove event to monitor the mouse pointer's movement over a specific <div> element identified as "mouseMoveDiv." The handler function extracts clientX and clientY properties from an event object that represents X-Y coordinates of said pointer. Subsequently, these are logged into console; thus offering real-time feedback on where exactly within our designated div area is the user positioning their cursor.

    <!DOCTYPE html><html><head><title>Mouse Move Event Example</title></head><body><div id="mouseMoveDiv" 
       style="width: 600px; height: 200px; background-color: lightgreen;">
       Please move you mouse inside thisDIV.</div><p id ="output"></p><script>const mouseMoveDiv = document.getElementById('mouseMoveDiv');const outputDiv = document.getElementById("output");
    
      mouseMoveDiv.addEventListener('mousemove',function(event){const x = event.clientX;const y = event.clientY;
         outputDiv.innerHTML +=Mouse moved to (${x}, ${y})+JSON.stringify(event)+"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Wheel Event

    This example showcases the wheel event, activated when the mouse wheel is rotated. The event listener is attached to a <div> element with the id "wheelDiv." When the user rotates the mouse wheel over this div, the associated function logs a message to the console, indicating that the mouse wheel has been rotated.

    <!DOCTYPE html><html><head><title>Wheel Event Example</title></head><body><div id="wheelDiv" 
       style="width: 600px; height: 200px; background-color: palevioletred;">
       Please bring the curser inside thisDIV and rotate the wheel of mouse.</div><p id ="output"></p><script>const wheelDiv = document.getElementById('wheelDiv');const outputDiv = document.getElementById("output");
    
      wheelDiv.addEventListener('wheel',function(event){
         outputDiv.innerHTML +='Mouse wheel rotated!'+ event +"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • addEventListener

    The JavaScript addEventListener() method is used to attach an event handler function to an HTML element. This allows you to specify a function that will be executed when a particular event occurs on the specified element.

    Events are a specific occurrence or action like user clicks, keypress or page loads. The browser detects these events and triggers associated JavaScript functions known as event handlers to respond accordingly.

    Developers employ the ‘addEventListener()’ method for linking particular HTML elements with specific function behaviours when those events occur. Examples of events include clicks, mouse movements, keyboard inputs, and document loading.

    Syntax

    The basic syntax for addEventListener() is as follows −

    element.addEventListener(event,function, options);

    Here element is an HTML element, such as a button, input or div – can be selected using methods like getElementById, getElementsByClassName, getElementsByTagName and querySelector; these are just a few examples. The event listener attaches to this particular element.

    Parameters

    The addEventListener() method accepts the following parameters −

    • event − a string that embodies the type of action − for instance, “click”, “mouseover”, or “keydown” among others; will serve as our trigger to execute the given function.
    • function − a named, anonymous or reference to an existing function is called when the specified event occurs; it’s essentially the operation that facilitates execution at predetermined instances.
    • options (optional) − it allows for the specification of additional settings particularly capturing or once behaviours related to the event listener.

    Examples

    Example: Alert on Clicking Button

    In this example, we will have a simple button being displayed which upon clicking shows an alert on the screen. The addeventlistener will be responsible for handling the event click which means it will call a function handleClick which throws an alert to the screen when the button is clicked. We make use of the getElementById to fetch the button we want to bind the event listener to.

    This is a commonly used event when it comes to submitting on forms, login, signup etc.

    <html><head><title>Click Event Example</title></head><body><p> Click the button below to perform an event </p><button id="myButton">Click Me</button><script>// Get the button elementconst button = document.getElementById("myButton");// Define the event handler functionfunctionhandleClick(){alert("Button clicked!");}// Attach the event listener to the button
    
      button.addEventListener("click", handleClick);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Colour Change on Mouse Over

    In this example we have a dig tag which will initially be of light blue colour. Upon hovering the mouse on this div tag, it will change to red and back to blue if we hover out.

    There are two events in this case, mouseover and mouseout. The mouseover means the mouse moves onto an element mouseout means the mouse movies out of an element.

    There are two functions here, one for mouseover and one for mouseout. Upon mouseover, the background colour property is set to light coral (a shade of red) and upon mouseout, the background colour is set to light blue.

    These types of mouse hover events are commonly seen when hovering over the navbar of a lot of websites.

    <html><head><title>Mouseover Event Example</title><style>
    
      #myDiv {
         width:600px;
         height:200px;
         background-color: lightblue;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id="myDiv"&gt;Hover over me&lt;/div&gt;&lt;script&gt;// Get the div elementconst myDiv = document.getElementById("myDiv");// Define the event handler functionfunctionhandleMouseover(){
      myDiv.style.backgroundColor ="lightcoral";}// Attach the event listener to the div
      myDiv.addEventListener("mouseover", handleMouseover);// Additional example: Change color back on mouseoutfunctionhandleMouseout(){
         myDiv.style.backgroundColor ="lightblue";}
      myDiv.addEventListener("mouseout", handleMouseout);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    There can be multiple event listeners for the same elements like in the case of 2nd example which has two event listeners (for mouseover and mouseout). Event listeners can be removed using the removeEventListener function. By passing a parameter in the options as once:true, we can ensure that the event listener is removed after being invoked once and this is important in certain case scenarios like payments.

    It is important to note that one should never use the "on" prefix for specifying events, this simply means for a click event, we should specify it as "click" and not "onclick".

  • DOM Events

    The DOM events are actions that can be performed on HTML elements. When an event occurs, it triggers a JavaScript function. This function can then be used to change the HTML element or perform other actions.

    Here are some examples of DOM events:

    • Click − This event occurs when a user clicks on an HTML element.
    • Load − This event occurs when an HTML element is loaded.
    • Change − This event occurs when the value of an HTML element is changed.
    • Submit − This event occurs when an HTML form is submitted.

    You can use the event handlers or addEventListener() method to listen to and react to the DOM events. The addEventListener() method takes two arguments: the name of the event and the function that you want to be called when the event occurs.

    The DOM events are also referred as Document Object Model events. It is used to interact with the DOM elements and manipulate the DOM elements from JavaScript when any event occurs.

    Let’s look at the below examples of DOM events.

    The onclick Event Type

    This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.

    Example

    Try the following example.

    <html><head><script>functionsayHello(){alert("Hello World")}</script></head><body><p>Click the following button and see result</p><form><input type ="button" onclick ="sayHello()" value ="Say Hello"/></form></body></html>

    The ondblclick Event Type

    We use the ‘ondblclick’ event handler in the code below with the element. When users double click the button, it calls the changeColor() function.

    In the changeColor() function, we change the color of the text. So, the code will change the text’s color when the user double-clicks the button.

    Example

    <html><body><h2 id ="text"> Hi Users!</h2><button ondblclick="changeColor()"> Double click me!</button><script>functionchangeColor(){
    
         document.getElementById("text").style.color ="red";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The onkeydown Event Type

    We used the 'keydown' event in the code below with the <input> element. Whenever the user will press any key, it will call the customizeInput() function.

    In the customizeInput() function, we change the background color of the input and the input text to red.

    Example

    <html><body><p> Enter charater/s by pressing any key  </p><input type ="text" onkeydown ="customizeInput()"><script>functioncustomizeInput(){var ele = document.getElementsByTagName("INPUT")[0];
    
         ele.style.backgroundColor ="yellow";
         ele.style.color ="red";}&lt;/script&gt;&lt;/body&gt;</pre>