Blog

  • 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>
  • Introduction to Events

    What is an Event ?

    JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page.

    When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

    Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.

    Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.

    Please go through this small tutorial for a better understanding HTML Event Reference.

    JavaScript Event Handlers

    Event handler can be used as an attribute of the HTML element. It takes the inline JavaScript or function execution code as a value.

    Whenever any event triggers, it invokes the inline JavaScript code or executes the callback function to perform the particular action.

    In simple terms, it is used to handle the events.

    Syntax

    Users can follow the syntax below to use event handlers with HTML elements.

    <div eventHandler ="JavaScript_code"></div>

    In the above syntax, you need to replace the ‘eventHandler’ with the actual event handler like ‘onclick’, ‘onmouseover’, etc. The ‘JavaScript_code’ should execute the function or run JavaScript inline.

    Example: Inline JavaScript with Event Handlers

    In the code below, we have created the <button> element. Also, we have used the ‘onclick’ event handler to capture the click event on the button.

    We have written the inline JavaScript code to handle the event. In the inline JavaScript code, the ‘this’ keyword represents the <button> element, and we change the button’s text color to red.

    <html><body><h2> Click the button to Change its text's color </h2><button onclick ="this.style.color='red'"> Click Me </button><div id ="output"></div></body></html>

    Example: Function with Event Handlers

    In the code below, we have created the <div> element and given style into the <head> section.

    We used the ‘onclick’ event handler with the <button> element, which calls the handleClick() function when the user clicks the button.

    The handleClick() function takes the ‘event’ object as a parameter. In the handleClick() function, we change the background color of the <div> element using JavaScript.

    <html><head><style>
    
      #test {
         width:600px;
         height:100px;
         background-color: red;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="test"&gt;&lt;/div&gt;&lt;br&gt;&lt;button onclick ="handleClick()"&gt; Change Div Color &lt;/button&gt;&lt;script&gt;functionhandleClick(event){var div = document.getElementById("test");
         div.style.backgroundColor ="blue";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Multiple Functions with Event Handlers

    In the code below, we have added the 'ommouseenter' event handler with the <div> element. We call the changeFontSize() and changeColor() functions when a user enters the mouse cursor in the <div> element.

    The changeFontSize() function changes the size of the text, and changeColor() function changes the color of the text.

    This way, you can invoke the multiple functions on the particular event.

    <html><head><style>
    
      #test {
         font-size:15px;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt; Hover over the below text to customize the font.&lt;/h2&gt;&lt;div id ="test" onmouseenter ="changeFontSize(); changeColor();"&gt; Hello World!&lt;/div&gt;&lt;br&gt;&lt;script&gt;functionchangeFontSize(event){
         document.getElementById("test").style.fontSize ="25px";}functionchangeColor(event){
         document.getElementById("test").style.color ="red";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Event Object

    The function that handles the event takes the 'event' object as a parameter. The 'event' object contains the information about the event and the element on which it occurred.

    There are various properties and methods are also available which can be used with the event object to get information.

    ObjectDescription
    EventIt is a parent of all event objects.

    Here is the list of different types of event objects. Each event object contains various events, methods, and properties.

    Object/TypeHandles
    AnimationEventIt handles the CSS animations.
    ClipboardEventIt handles the changes of the clipboard.
    DragEventIt handles the drag-and-drop events.
    FocusEventTo handle the focus events.
    HashChangeEventIt handles the changes in the anchor part of the URL.
    InputEventTo handle the form inputs.
    KeyboardEventTo handle the keyboard interaction by users.
    MediaEventIt handles the media-related events.
    MouseEventTo handle the mouse interaction by users.
    PageTransitionEventTo handle the navigation between web pages.
    PopStateEventIt handles the changes in the page history.
    ProgressEventTo handle the progress of the file loading.
    StorageEventTo handle changes in the web storage.
    TouchEventTo handle touch interaction on the devices screen.
    TransitionEventTo handle CSS transition.
    UiEventTo handle the user interface interaction by users.
    WheelEventTo handle the mouse-wheel interaction by users.

  • Geolocation API

    Geolocation API

    The Geolocation API is a web API that provides a JavaScript interface to access the user’s geographical location data. A Geolocation API contains the various methods and properties that you can use to access the user’s location on your website.

    It detects the location of the user’s using the device’s GPS. The accuracy of the location depends on the accuracy of the GPS device.

    As location compromises the users’ privacy, it asks for permission before accessing the location. If users grant permission, websites can access the latitude, longitude, etc.

    Sometimes, developers need to get the user’s location on the website. For example, if you are creating an Ola, Uber, etc. type applications, you need to know the user’s location to pick them up for the ride.

    The Geolocation API allows users to share the location with a particular website.

    Real-time use cases of the Geolocation API

    Here are the real-time use cases of the Geolocation API.

    • To get the user’s location coordinates, show them on the map.
    • To tag the user’s location on the photograph.
    • To suggest nearby stores, food courts, petrol pumps, etc., to users.
    • To get the current location for the product or food delivery.
    • To pick up users for the ride from their current location.

    Using the Geolocation API

    To use the Geolocation API, you can use the ‘navigator’ property of the window object. The Navigator object contains the ‘geolocation’ property, containing the various properties and methods to manipulate the user’s location.

    Syntax

    Follow the syntax below to use the Geolocation API.

    var geolocation = window.navigator.geolocation;ORvar geolocation = navigator.geolocation;

    Here, the geolocation object allows you to access the location coordinates.

    Example: Checking the browser support

    Using the navigator, you can check whether the user’s browser supports the Geolocation.geolocation property.

    The code below prints the message accordingly whether the Geolocation is supported.

    First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");if(navigator.geolocation){
    
      output.innerHTML +="Geolocation is supported by your browser."}else{
      output.innerHTML +="Geolocation is not supported by your browser."}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Geolocation is supported by your browser.
    

    Geolocation Methods

    Here are the methods of the Geolocation API.

    MethodDescription
    getCurrentPosition()It is used to retrieve the current geographic location of the website user.
    watchPosition()It is used to update the user's live location continuously.
    clearWatch()To clear the ongoing watch of the user's location using the watchPosition() method.

    The Location Properties

    The getCurrentPosition() method executes the callback function you passed as an argument. The callback function takes the object as a parameter. The parametric object contains various properties with information about the user's location.

    Here, we have listed all properties of the location object in the table below.

    PropertyTypeDescription
    coordsobjectsIt is an object you get as a parameter of the callback function of the getCurrentPosition() method. It contains the below properties.
    coords.latitudeNumberIt contains the latitude of the current location in decimal degrees. The value range is [-90.00, +90.00].
    coords.longitudeNumberIt contains the longitude of the current location in decimal degrees. The value range is [-180.00, +180.00].
    coords.altitudeNumberIt is an optional property, and it specifies the altitude estimate in meters above the WGS 84 ellipsoid.
    coords.accuracyNumberIt is also optional and contains the accuracy of the latitude and longitude estimates in meters.
    coords.altitudeAccuracyNumber[Optional]. It contains the accuracy of the altitude estimate in meters.
    coords.headingNumber[Optional]. It contains information about the device's current direction of movement in degrees counting clockwise relative to true north.
    coords.speedNumber[Optional]. It contains the device's current ground speed in meters per second.
    timestampdateIt contains the information about the time when the location information was retrieved, and the Position object created.

    Getting User's Location

    You can use the getCurrentPosition() method to get the user's current location.

    Syntax

    Users can follow the syntax below to get the user's current position using the getCurrentPosition() method.

    navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

    Parameters

    The getCurrentPosition() object takes 3 parameters.

    • successCallback − This function will be called when the method successfully retrieves the user's location.
    • errorCallback − This function will be called when the method throws an error while accessing the user's location.
    • Options − It is an optional parameter. It is an object containing properties like timeout, maxAge, etc.

    Permitting the website to access your location

    Whenever any website tries to access your location, the browser pops up the permission alert box. If you click the 'allow, it can fetch your location details. Otherwise, it throws an error.

    You can see the permission pop-up in the image below.

    Example

    In the below code, we use the getCurrentPosition() method to get the user's location. The method calls the getCords() function to get the current location.

    In the getCords() function, we print the value of the various properties of the cords object.

    First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><h3> Location Information </h3><button onclick ="findLocation()"> Find Location </button><p id ="output"></p><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){
    
        navigator.geolocation.getCurrentPosition(getCords);//}else{
        output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
      output.innerHTML +="The current position is: &lt;br&gt;";
      output.innerHTML +="Latitude: "+ coords.coords.latitude +"&lt;br&gt;";
      output.innerHTML +="Longitude: "+ coords.coords.longitude +"&lt;br&gt;";
      output.innerHTML +="Accuracy: "+ coords.coords.accuracy +"&lt;br&gt;";
      output.innerHTML +="Altitude: "+ coords.coords.altitude +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Geolocation Errors

    The getCurrentPosition() method takes the callback function as a second parameter to handle the error. The callback function can have an error object as a parameter.

    In the below cases, an error can occur.

    • When the user has denied access to the location.
    • When location information is not available.
    • When the request for the location is timed out.
    • It can also generate any random error.

    Here is the list of properties of the error object.

    PropertyTypeDescription
    codeNumberIt contains the error code.
    messageStringIt contains the error message.

    Here is the list of different error codes.

    CodeConstantDescription
    0UNKNOWN_ERRORWhen methods of the geolocation object cant retrieve the location, it returns the code 0 for unknown error.
    1PERMISSION_DENIEDWhen the user has denied the permission to access the location.
    2POSITION_UNAVAILABLEWhen it cant find the location of the device.
    3TIMEOUTWhen the method of the geolocation object cant find the users position.

    Example: Error Handling

    We use the getCurrentPosition() method in the findLocation() function in the below code. We have passed the errorCallback() function as a second parameter of the getCurrentPosition() method to handle the errors.

    In the errorCallback() function, we use the switch case statement to print the different error messages based on the error code.

    When you click the Find Location button, it will show you a pop-up asking permission to access the location. If you click on the 'block, it will show you an error.

    First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><div id ="output"></div><button onclick ="findLocation()"> Find Location </button><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){
    
    navigator.geolocation.getCurrentPosition(getCords, errorCallback);//}else{
    output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
    output.innerHTML +="The current position is: <br>"; output.innerHTML +="Latitude: "+ coords.coords.latitude +"<br>"; output.innerHTML +="Longitude: "+ coords.coords.longitude +"<br>";}// Function to handle errorfunctionerrorCallback(err){switch(err.code){case err.PERMISSION_DENIED:
      output.innerHTML +="You have denied to access your device's location";break;case err.POSITION_UNAVAILABLE:
      output.innerHTML +="Your position is not available.";break;case err.TIMEOUT:
      output.innerHTML +="Request timed out while fetching your location.";break;case err.UNKNOWN_ERROR:
      output.innerHTML +="Unknown error occurred while fetching your location.";break;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Geolocation Options

    The getCurrentPosition() method takes the object containing the options as a third parameter.

    Here is the list of options you can pass as a key to the option object.

    PropertyTypeDescription
    enableHighAccuracyBooleanIt represents whether you want to get the most accurate location.
    timeoutNumberIt takes a number of milliseconds as a value for that much time you want to wait to fetch the location data.
    maximumAgeNumberIt takes the milliseconds as a value, specifying the maximum age of the cached location.

    Example

    The below code finds the most accurate location. Also, we have set milliseconds to the maximumAge, and timeout properties of the options object.

    First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><div id ="output"></div><button onclick ="findLocation()"> Find Location </button><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){// Options for geolocationconst options ={
    
        enableHighAccuracy:true,
        timeout:5000,
        maximumAge:0};
      navigator.geolocation.getCurrentPosition(getCords, errorfunc, options);}else{
      output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
    output.innerHTML +="The current position is: &lt;br&gt;";
    output.innerHTML +="Latitude: "+ coords.coords.latitude +"&lt;br&gt;";
    output.innerHTML +="Longitude: "+ coords.coords.longitude +"&lt;br&gt;";}functionerrorfunc(err){
    output.innerHTML +="The error message is - "+ err.message +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Watching the Current Location of the User

    The watchPosition() method allows you to track the live location of users. It returns the ID, which we can use with the clearWatch() method when you want to stop tracking the user.

    Syntax

    Follow the syntax below to use the watchPosition() method to track the live location of users.

    var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)

    The errorCallback and options are optional arguments.

    If you want to stop tracking the user, you can follow the syntax below.

    navigator.geolocation.clearWatch(id);

    The clearWatch() method takes the id returned by the watchPosition() method as an argument.

    Example

    In the below code, we used the geolocation object's watchPosition () method to get the user's continuous position.

    We used the getCords() function as a callback of the watchPosition() method, where we print the latitude and longitude of the user's position.

    In the findLocation() method, we used the setTimeOut() method to stop tracking after 30 seconds.

    In the output, you can observe that the code prints the user's position multiple times.

    First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><button onclick ="findLocation()"> Find Location </button><div id ="output"></div><script>let output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){let id = navigator.geolocation.watchPosition(getCoords);setTimeout(function(){
    
          navigator.geolocation.clearWatch(id);
          output.innerHTML +="&lt;br&gt;Tracking stopped!";},30000);// Stop tracking after 30 seconds.}else{
        output.innerHTML +="&lt;br&gt;Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCoords(location){let latitude = location.coords.latitude;let longitude = location.coords.longitude;
      output.innerHTML +=&amp;lt;br&amp;gt; Latitude: ${latitude}, Longitude: ${longitude};}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Fetch API

    What is a Fetch API?

    The JavaScript Fetch API is a web API that allows a web browser to make HTTP request to the web server. In JavaScript, the fetch API is introduced in the ES6 version. It is an alternative of the XMLHttpRequest (XHR) object, used to make a ‘GET’, ‘POST’, ‘PUT’, or ‘DELETE’ request to the server.

    The window object of the browser contains the Fetch API by default.

    The Fetch API provides fetch() method that can be used to access resources asynchronously across the web.

    The fetch() method allows you to make a request to the server, and it returns the promise. After that, you need to resolve the promise to get the response received from the server.

    Syntax

    You can follow the syntax below to use the fetch() API in JavaScript

    window.fetch(URL,[options]);ORfetch(URL,[options]);

    Parameters

    The fetch() method takes two parameters.

    • URL − It is an API endpoint where you need to make a request.
    • [options] − It is an optional parameter. It is an object containing the method, headers, etc., as a key.

    Return value

    It returns the promise, which you can solve using the ‘then…catch’ block or asynchronously.

    Handling Fetch() API Response with ‘then…catch’ Block

    The JavaScript fetch() API returns the promise, and you can handle it using the ‘then…catch’ block.

    Follow the syntax below to use the fetch() API with the ‘then…catch’ block.

    fetch(URL).then(data=>{// Handle data}).catch(err=>{// Handle error})

    In the above syntax, you can handle the ‘data’ in the ‘then’ block and the error in the ‘catch’ block.

    Example

    In the below code, we fetch the data from the given URL using the fetch() API. It returns the promise we handle using the ‘then’ block.

    First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');constURL='https://jsonplaceholder.typicode.com/todos/5';fetch(URL).then(res=> res.json()).then(data=>{
    
         output.innerHTML +="The data from the API is: "+"&lt;br&gt;";
      	 output.innerHTML +=JSON.stringify(data);});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The data from the API is:
    {"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}
    

    Handling Fetch() API Response Asynchronously

    You can also solve the promise returned by the fetch() API asynchronously using the async/await keyword.

    Syntax

    Users can follow the syntax below to use the async/await keywords with the fetch() API.

    let data =awaitfetch(URL);
    data =await data.json();

    In the above syntax, we used the 'await' keyword to stop the code execution until the promise gets fulfilled. After that, we again used the 'await' keyword with the data.json() to stop the execution of the function until it converts the data into the JSON format.

    Example

    In the code below, we have defined the getData()asynchronous function to fetch the to-do list data from the given URL using the fetch() API. After that, we convert the data into JSON and print the output on the web page.

    <html><body><div id ="output"></div><script>asyncfunctiongetData(){let output = document.getElementById('output');letURL='https://jsonplaceholder.typicode.com/todos/6';let data =awaitfetch(URL);
    
      data =await data.json();
      output.innerHTML +="The data from the API is: "+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(data);}getData();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The data from the API is:
    {"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}
    

    Options with Fetch() API

    You can also pass the object as a second parameter containing the options as a key-value pair.

    Syntax

    Follow the syntax below to pass the options to the Fetch() API.

    fetch(URL,{
    
    method:"GET",
    body:JSON.stringify(data),
    mode:"no-cors",
    cache:"no-cache",
    credentials:"same-origin",
    headers:{"Content-Type":"application/json",},
    redirect:"follow",})</pre>

    Options

    Here, we have given some options to pass to the fetch() API.

    • method − It takes the 'GET', 'POST', 'PUT', and 'DELETE' methods as a value based on what kind of request you want to make.
    • body − It is used to pass the data into the string format.
    • mode − It takes the 'cors', 'no-cors', 'same-origin', etc. values for security reasons.
    • cache − It takes the '*default', 'no-cache', 'reload', etc. values.
    • credentials − It takes 'same-origin', 'omit', etc. values.
    • headers − You can pass the headers with this attribute to the request.
    • redirect − If you want users to redirect to the other web page after fulfilling the request, you can use the redirect attribute.

    Example: Making a GET Request

    In the below code, we have passed the "GET" method as an option to the fetch() API.

    Fetch () API fetches the data from the given API endpoint.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");let options ={
    
         method:'GET',}letURL="https://dummy.restapiexample.com/api/v1/employee/2";fetch(URL, options).then(res=&gt; res.json()).then(res=&gt;{
            output.innerHTML +="The status of the response is - "+ res.status +"&lt;br&gt;";
            output.innerHTML +="The message returned from the API is - "+ res.message +"&lt;br&gt;";
            output.innerHTML +="The data returned from the API is - "+JSON.stringify(res.data);}).catch(err=&gt;{
            output.innerHTML +="The error returned from the API is - "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the response is - success
    The message returned from the API is - Successfully! Record has been fetched.
    The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}
    

    Example (Making a POST Request)

    In the below code, we have created the employee object containing the emp_name and emp_age properties.

    Also, we have created the options object containing the method, headers, and body properties. We use the 'POST' as a value of the method and use the employee object after converting it into the string as a body value.

    We make a POST request to the API endpoint using the fetch() API to insert the data. After making the post request, you can see the response on the web page.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");let employee ={"emp_name":"Sachin","emp_age":"30"}let options ={
    
         method:'POST',// To make a post request
         headers:{'Content-Type':'application/json;charset=utf-8'},
         body:JSON.stringify(employee)}letURL="https://dummy.restapiexample.com/api/v1/create";fetch(URL, options).then(res=&gt; res.json())// Getting response.then(res=&gt;{
            output.innerHTML +="The status of the request is : "+ res.status +"&lt;br&gt;";
            output.innerHTML +="The message returned from the API is : "+ res.message +"&lt;br&gt;";
            output.innerHTML +="The data added is : "+JSON.stringify(res.data);}).catch(err=&gt;{
            output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the request is : success
    The message returned from the API is : Successfully! Record has been added.
    The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}
    

    Example (Making a PUT Request)

    In the below code, we have created the 'animal' object.

    Also, we have created the options object. In the options object, we added the 'PUT' method, headers, and animal objects as a body.

    After that, we use the fetch() API to update the data at the given URL. You can see the output response that updates the data successfully.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");let animal ={"name":"Lion","color":"Yellow","age":10}let options ={
    
         method:'PUT',// To Update the record
         headers:{'Content-Type':'application/json;charset=utf-8'},
         body:JSON.stringify(animal)}letURL="https://dummy.restapiexample.com/api/v1/update/3";fetch(URL, options).then(res=&gt; res.json())// Getting response.then(res=&gt;{
            console.log(res);
            output.innerHTML +="The status of the request is : "+ res.status +"&lt;br&gt;";
            output.innerHTML +="The message returned from the API is : "+ res.message +"&lt;br&gt;";
            output.innerHTML +="The data added is : "+JSON.stringify(res.data);}).catch(err=&gt;{
            output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the request is : success
    The message returned from the API is : Successfully! Record has been updated.
    The data added is : {"name":"Lion","color":"Yellow","age":10}
    

    Example (Making a DELETE Request)

    In the below code, we make a 'DELETE' request to the given URL to delete the particular data using the fetch() API. It returns the response with a success message.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");let options ={
    
         method:'DELETE',// To Delete the record}letURL=" https://dummy.restapiexample.com/api/v1/delete/2";fetch(URL, options).then(res=&gt; res.json())// After deleting data, getting response.then(res=&gt;{
    output.innerHTML +="The status of the request is : "+ res.status +"<br>"; output.innerHTML +="The message returned from the API is : "+ res.message +"<br>"; output.innerHTML +="The data added is - "+JSON.stringify(res.data);}).catch(err=>{
    	    output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the request is : success
    The message returned from the API is : Successfully! Record has been deleted
    The data added is - "2"
    

    Advantages of Using the Fetch() API

    Here are some benefits of using the fetch() API to interact with third-party software or web servers.

    • Easy Syntax − It provides a straightforward syntax to make an API request to the servers.
    • Promise-based − It returns the promise, which you can solve asynchronously using the 'then...catch' block or 'async/await' keywords.
    • JSON handling − It has built-in functionality to convert the string response data into JSON data.
    • Options − You can pass multiple options to the request using the fetch() API.
  • Worker API

    Web Worker API

    The worker API is a web API that allows us to run JavaScript code in the background thread. Whenever the web page loads in the browser, it becomes interactive after every <script> tag loads in the browser. Web workers allows users to interact with the web page without loading the whole JavaScript code in the browser. It increases the response time of the web page.

    Create a Web Worker File

    To create a web worker, you need to write a script in the external file, which you need to execute in a different file.

    The filename should have a ‘.js’ extension.

    In the below JavaScript code, we defined the counter() function. We used the setTimeout() method inside the function to call the counter() function after every 1000 milliseconds.

    The important part of the code is the postMessage() method. It is used to send the data in the main thread.

    functioncounter(){postMessage(data);// To send data to the main threadsetTimeout("counter()",1000);}counter();

    Check for Web Worker Support

    You should check that your browser supports the web worker or not before creating the web worker. You can use the typeof operator to check for this.

    if(typeof(Worker)!=="undefined"){//"Web worker is supported by your browser!";}else{//"Web worker is not supported by your browser!";}

    Create a Web Worker Object

    After creating the external JavaScript file, you need to create a new Worker object by passing the path of the external JavaScript file as an argument, as shown below.

    const workerObj =newWorker("testWorker.js");

    To get the message main thread from the worker file, which we send using the postMessage() method, you can use the ‘onmessage’ event on the worker object, as shown below.

    workerObj.onmessage=function(e){// Use the event.data};

    Terminate the Execution of the Web Worker

    When you start the execution of the web worker script, it continues the execution until you terminate the execution.

    You can use the terminate() method to terminate the execution of the web worker as shown below.

    workerObj.terminate();

    Example: Complete Program of Web Worker

    Filename: – index.html

    In the below code, we have defined the startWorker() and stopWorker() functions to start and stop the execution of the worker.

    In the startWorker() function, first, we check whether the browser supports the workers. After that, we check whether any instance of the worker is running. If not, we create a new instance of the Worker object using the script defined in the external file.

    After that, we added the onmessage event on the worker object. So, whenever it gets data from the external script file, it prints it and performs other operations.

    In the stopWorker() function, we use the terminate() method with the workerObj object to terminate the execution of the worker.

    <html><body><button onclick ="startWorker()"> Start Counter </button><button onclick ="stopWorker()"> Stop Counter </button><div id ="output"></div><script>let output = document.getElementById('output');let workerObj;functionstartWorker(){if(typeof(Worker)!=="undefined"){if(typeof workerObj ==="undefined"){
    
            workerObj =newWorker("app.js");
            workerObj.onmessage=function(event){//Getting the message from web worker
               output.innerHTML +="Event data is: "+ event.data +"&lt;br&gt;";};}}else{
         output.innerHTML +="Web worker is not supported by your browser.";}}functionstopWorker(){// To stop the web worker.if(typeof workerObj !=="undefined"){
         workerObj.terminate();
         workerObj =undefined;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Filename: - app.js

    In the below code, we have defined the counter() function. In the counter() function, we used the setTimeOut() method to call the counter() function after every second. It also posts the data into the main thread using the postMessage() method.

    var i =0;functiontimedCount(){
       i = i +1;postMessage(i);setTimeout("timedCount()",500);}timedCount();

    Output

    To run the above code, you need to make sure that the index.html and app.js file is on the live web server. You can also use the localhost. Also, make sure to add the correct path for the app.js file in the Worker object inside the index.html file.

    Web Worker API

    You can also use multiple workers in the same file to run multiple scripts in the background.

    Web Worker Use Cases

    The above example is simple, and in such cases, you dont need to use web workers, but it is only for demonstrations.

    Here are the real-time use cases of the web workers.

    • When you need to execute large or complex mathematical script
    • In the HTML games, you may use web workers
    • If you want to improve the website performance
    • In parallel downloads, when you need to execute multiple threads
    • For the background data synchronization
    • In the machine learning
    • For generating reports
    • To process audio and videos

    Web Workers and the DOM

    As you need to define the scripts for the web workers in the external file, you can't use the below objects in the external file.

    • The window object
    • The document object
    • The parent object

    However, you can use the below objects in the web workers.

    • The location object
    • The navigator object
    • The Application Cache
    • Importing external script using importScripts()
    • XMLHttpRequest
  • Forms API

    Web Forms API

    JavaScript Forms API is a web API that allows us to interact with and manipulate HTML forms. It provides a set of methods and properties that are used to perform client-side form validation. Its also helpful to ensure data integrity before form submission. The forms API also referred to as Form Validation API or Constraint Validation API.

    Here, we will discuss how to use various methods and properties to validate the form data using JavaScript.

    Constraint Validation DOM Methods

    In JavaScript, the constraint validation DOM method validates the input value by referencing the input fields. It validates the input value based on the HTML attributes you have used with the input.

    After validating the input value, it returns a boolean value, representing whether the input value is valid.

    Here is the list of the constraint validation methods.

    MethodDescription
    checkValidity()It returns a boolean value based on whether the input element contains a valid value.
    setCustomValidity()It is used to set the custom message to the validationMessage property.

    Syntax

    We can follow the syntax below to use the form validation methods.

    element.checkValidity()OR
    element.setCustomValidity(message);

    In the above syntax, you need to access the element using the selector and take it as a reference of the checkValidity() or setCustomValidity() method. The setCustomValidity() method takes the string message as an argument.

    Example: Using the checkValidity() method

    We created the number input in the code below and set 10 to the min attribute.

    In the validateInput() function, we access the number input using the id and use the checkValidity() to validate the value of the number input.

    If checkValidity() method returns false, we print the validation message. Otherwise, we print the numeric value.

    <html><body><input type ="number" min ="10" id ="num" required><p id ="output"></p><button onclick ="validateInput()"> Validate Number </button><script>const output = document.getElementById("output");functionvalidateInput(){let num = document.getElementById("num");if(num.checkValidity()==false){
    
            output.innerHTML ="Please enter a number greater than 10";}else{
            output.innerHTML ="Your number is "+ num.value;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Using the setCustomValidity() Method

    In the below code, we have defined the number input to take the users age in the input.

    In the validateAge() function, we access the age input using its id and perform the custom validation on the input value. Based on the validation, we use the setCustomValidity() to set the custom validation message.

    At last, we use the reportValidity() method to show the validation message set using the setCustomValidity() method.

    You can enter the age below 18, and observe the validation message.

    <html><body><form><label> Enter your age:</label><input type ="number" id ="age" required><br><br><button type ="button" onclick ="validateAge()"> Validate Age </button></form><div id ="message"></div><script>functionvalidateAge(){const ageInp = document.getElementById("age");const output = document.getElementById("message");const age =parseInt(ageInp.value);if(isNaN(age)){
    
            ageInp.setCustomValidity("Please enter a valid number.");}elseif(age &lt;18){
            ageInp.setCustomValidity("You must be at least 18 years old.");}else{
            ageInp.setCustomValidity("");// To remove custom error message
            output.innerHTML ="Age is valid!";}
         ageInp.reportValidity();// To display custom validation message}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Constraint Validation DOM Properties

    JavaScript also contains the DOM properties for constraint validation. It is used to check the particular validation of the input value.

    Here, we have listed all DOM properties that can be used for the constraint validation.

    PropertyDescription
    validityIt contains multiple properties to perform the particular validation on the input element.
    validationMessageIt contains the validation message when the input element doesn't contain valid data.
    willValidateIt represents whether the input data will be validated.

    Properties of the 'validity' Property

    In JavaScript, each element has the 'validity' property, containing multiple properties. You can use the particular property of the 'validation' property to perform the validation.

    Here, we have listed all properties of the 'validity' property.

    PropertyDescription
    customErrorIt contains a true boolean value when you set the custom validity message.
    patternMismatchWhen the parent element's value doesn't match the pattern, it sets true.
    rangeOverflowIt returns a boolean value based on whether the input value is greater than the max attribute's value.
    rangeUnderflowIt returns a boolean value based on whether the input value is less than the min attribute's value.
    stepMismatchIt returns a boolean value based on whether the step is mismatching in the numeric input.
    tooLongIf the length of the input element's value is greater than the maxLength attribute's value, it returns true. Otherwise, it returns false.
    typeMismatchWhen the type of entered value doesn't match the 'type' attribute's value, it returns true.
    valueMissingIt returns a boolean value based on whether the input element is empty.
    validIt returns true when the input element is valid.

    Syntax

    Users can follow the syntax below to use the properties of the validation property.

    element.validity.property;

    You can use the different properties of the validity property of the element to validate the input elements value.

    Example

    In the below code, we have defined the number input and set 300 for the value of the max attribute.

    In the validateNumber() function, we use the rangeOverflow property of the validity property of the input element to check whether the input value is greater than 300.

    If the rangeOverflow property returns true, we print the Number is too large. Otherwise, we print the numeric value.

    <html><body><form><label> Enter Any Number:</label><input type ="number" id ="num" max ="300" required><br><br><button type ="button" onclick ="validateNumber()"> Validate Number </button></form><div id ="output"></div><script>const output = document.getElementById('output');functionvalidateNumber(){const numInput = document.getElementById('num');if(numInput.validity.rangeOverflow){
    
            output.innerHTML ="Number is too large";}else{
            output.innerHTML ="Number is valid";}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In the below code, we have defined the text input.

    In the validateText() function, we access the string input. After that, we used the valueMissing property of the validity property to check whether the input value is empty.

    In the output, you can keep the input value empty, click the validate text button and observe the error message.

    <html><body><form><label> Enter any text:</label><input type ="text" id ="str" required><br><br><button type ="button" onclick ="validateText()"> Validate Text </button></form><div id ="output"></div><script>const output = document.getElementById('output');functionvalidateText(){const strInput = document.getElementById('str');if(strInput.validity.valueMissing){
    
            output.innerHTML ="Please enter a value.";}else{
            output.innerHTML ="You have entered "+ strInput.value +".";}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    You can also use the other properties of the validity property to validate the form input data. If the data is not valid, you can show the custom error message using the setCustomValidity() method.