JavaScript – Form Events ”; Previous Next 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 Event Description onsubmit Triggered when a form is submitted. It”s often used for form validation before data is sent to the server. onreset Triggered when the form is reset, allowing you to perform actions when the user resets the form. onchange Triggered when the value of a form element (input, select, textarea) changes. Commonly used for user input validation or dynamic updates. oninput Triggered immediately when the value of an input element changes, allowing for real-time handling of user input. onfocus Triggered 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. onblur Triggered 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> function handleChange() { // Perform actions when the dropdown selection changes var selectedCountry = document.getElementById(”country”).value; document.getElementById(“txt”).textContent= “Selected country: “+selectedCountry; } </script> </body> </html> 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> function validateForm() { var username = document.getElementById(”username”).value; var password = document.getElementById(”password”).value; // Perform validation if (username === “” || password === “”) { alert(“Please fill in all fields”); return false; // Prevent form submission } alert(“Form submitted! Username is:”+username+”,Password is:”+password); return true; // 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> function resetForm() { // Perform actions when the form is reset alert(“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”); function handleInput() { // Perform actions as the user types var searchInput = document.getElementById(”search”).value; messageElement.innerHTML+=”Search input: ” + searchInput+”<br>”; } </script> </body> </html> 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”); function handleFocus() { // Perform actions when the input gets focus output.innerHTML += “Input has focus” + “<br>”; } function handleBlur() { // Perform actions when the input loses focus output.innerHTML += “Input lost focus” + “<br>”; } </script> </body> </html> Print Page Previous Next Advertisements ”;
Category: javascript
JavaScript – var Keyword
JavaScript – var Keyword ”; Previous Next The var keyword in JavaScript is used to declare variables. Before ES6, there was only var keyword to declare a variable. In ES6, let and const keywords were introduced as a better way to declare variables. It is advised to use let instead of var to declare a variable. If you are targeting older version of browser, you can use var. In JavaScript, variables are the data storage container. You can use the variables to store any type of data. For example, string, number, boolean, object, etc. A variable declared with var keyword has function scope. Whereas a variable declared with let has block scope. Syntax Follow the syntax below to define the variable using the ”var” keyword. var identifier; var identifier = value; Here, the identifier can be a valid variable name. In the JavaScript – Variables chapter, we have already discussed the rules to define valid identifiers. You may assign or not value to the variable while declaring it using the JavaScript ”var” keyword. Example In the below code, we have defined the 3 variables using the ”var” keyword. In the num1 variable, we have stored the numeric value. In the str1 variable, we have stored the string value; in the bool variable, we have stored the boolean value. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <div id = “output3”> </div> <script> var num1 = 30; var str1 = “Hello World!”; var bool = true; document.getElementById(”output1”).innerHTML = num1; document.getElementById(”output2”).innerHTML = str1; document.getElementById(”output3”).innerHTML = bool; </script> </body> </html> Output 30 Hello World! true JavaScript Variable Scopes The scope of the variable defined using the JavaScript ”var” keyword has a function scope or global scope. JavaScript Function Scope When you define the variable inside the function using the var keyword, it can be accessible inside the function anywhere. Even if you define the variable using the var keyword inside the particular block inside the function, it can be accessible anywhere. Let”s understand the function scope with the example below. Example In the below code, we have defined the variable ”x” inside the function. We have also defined the variable ”y” inside the block, which is inside the function. After that, we access the variables x and y inside the function. <html> <body> <div id = “demo1”> </div> <div id = “demo2″> </div> <script> function demo() { var x = 10; { var y = 20; // x and y both can be accessible here } document.getElementById(”demo1”).innerHTML = “X == ” + x; document.getElementById(”demo2”).innerHTML = “Y == ” + y; } demo(); </script> </body> </html> Output X == 10 Y == 20 If you define the variable using the let keyword inside the block, which is inside the function, and try to access it outside the block, it will throw an error. JavaScript Global Scope It becomes the global variable if you define the variable using the ”var” keyword outside the function or a particular block. After that, you can access the variable anywhere inside the code using the window object. Example We have defined the ”num1” global variable in the code below. After that, we access the ”num1” variable inside the function using and without using the window object. <html> <body> <div id = “output”> </div> <script> const output = document.getElementById(”output”); var num1 = 10; function sum(num2) { output.innerHTML += “num1 + num2 = ” + (num1 + num2) + “<br>”; output.innerHTML += “window.num1 + num2 = ” + (window.num1 + num2); } sum(20); </script> </body> </html> Output num1 + num2 = 30 window.num1 + num2 = 30 JavaScript Variable Hoisting The variable defined using the ”var” keyword is hoisted at the top of its scope. It means JavaScript adds the declaration of the variable at the top of its scope. So you can access the variable before the declaration of the variable. Example In the below code, we have initialized the variable ”a” and printed its value before its declaration. The code runs without error, as the variable defined using the var keyword is hoisted at the top of its scope. <html> <body> <div id = “output”>Value of the variable a is: </div> <script> function checkHoisting() { a = 98; document.getElementById(”output”).innerHTML += a; var a; } // You can”t access the variable a here. checkHoisting(); </script> </body> </html> Output Value of the variable a is: 98 The above JavaScript code is similar to the below code. var a; a = 98; document.getElementById(”output”).innerHTML += a; Redeclaration of variable defined using the ”var” keyword You can redeclare the variables using the ”var” keyword, and the code will run without any error. If you have initialized the last duplicate variable with the latest value, it will contain that value. But if you don”t initialize the last duplicate variable, the variable will contain its previous value without losing it. Example In the code below, we have defined the variable ”a” two times and initialized it with different values. You can observe in the output that variable ”a” contains the last value. We have defined the variable ”a” a third time and haven”t initialized it. So, it contains the value of the 2nd ”a” variable. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); var a = 10; var a = 20; output.innerHTML += “The value of the a is: ” + a + “<br>”; var a; output.innerHTML += “The value of the a is: ” + a; </script> </body> </html> Output The value of the a is: 20 The value of the a is: 20 If you define the duplicate variables in the different scopes, it can have value according to where you access the variable. Example In the code below, we have defined the ”num” variable outside and inside the function. When you access it inside or outside the function, it prints the different values. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); var num = 10; function printNum()
JavaScript – Error Handling
JavaScript – Errors & Exceptions Handling ”; Previous Next Error handling in JavaScript is a process to detect and handle errors that occurs during the execution of a program. Errors can be a syntax, runtime or logical errors. An error occurred during the execution of the program is called a runtime error or an exception. In JavaScript, errors can occur due to programming mistakes, incorrect user input, etc. Errors can disrupt code execution and lead to bad user experience. Effective error & exception handling is required for building robust, reliable and user friendly applications in JavaScript. What is an Error? An error is an event that occurs during the execution of a program that prevents it from continuing normally. Errors can be caused by a variety of factors, such as syntax errors, runtime errors, and logical errors. Syntax Errors Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript. For example, the following line causes a syntax error because it is missing a closing parenthesis. <script> window.print(); </script> When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected, and the rest of the code in other threads gets executed, assuming nothing in them depends on the code containing the error. Runtime Errors (Exceptions) Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). For example, the following line causes a runtime error because the syntax is correct here, but at runtime, it is trying to call a method that does not exist. <script> window.printme(); </script> Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution. There are many JavaScript runtime errors (exceptions), some are as follows − ReferenceError − Trying to access an undefined variable/ method. TypeError − Attempting an operation on incompatible data types. RangeError − A value exceeds the allowed range. Logical Errors Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and do not get the expected result. For example, when you divide any numeric value with 10, it returns undefined. <script> let num = 10/0; </script> What is Error Handling? Whenever any error occurs in the JavaScript code, the JavaScript engine stops the execution of the whole code. If you handle such errors in the proper way, you can skip the code with errors and continue to execute the other JavaScript code. You can use the following mechanisms to handle the error. try…catch…finally statements throw statements the onerror() event handler property Custom Errors The try…catch…finally Statement The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try…catch…finally construct as well as the throw operator to handle exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors. Here is the try…catch…finally block syntax − <script> try { // Code to run [break;] } catch ( e ) { // Code to run if an exception occurs [break;] } [ finally { // Code that is always executed regardless of // an exception occurring }] </script> The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch. Example Here is an example where we are trying to call a non-existing function which in turn is raising an exception. Let us try to catch this exception using try…catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user. You can use finally block which will always execute unconditionally after the try/catch. <html> <head> <script> try { var a = 100; alert(myFunc(a)); } catch (e) { alert(e); } finally { alert(“Finally block will always execute!” ); } </script> </head> <body> <p>Exception handling using try…catch…finally statements</p> </body> </html> Output Exception handling using try…catch…finaly statements The throw Statement You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action. Example The following example demonstrates how to use a throw statement. <html> <head> <script> function myFunc() { var a = 100; var b = 0; try { if ( b == 0 ) { throw( “Divide by zero error.” ); } else { var c = a / b; } } catch ( e ) { alert(“Error: ” + e ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = “button” value = “Click Me” onclick = “myFunc();” /> </form> </body> </html> Output Click the following to see the result: Click Me You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try…catch block. The onerror Event Handler Property The onerror event handler was the first feature to facilitate error handling in JavaScript. The onerror is an event handler property of the ”window” object, which automatically triggers when any error occurs on any element of the web page. You can call the callback function when any error occurs to handle the
JavaScript – Location Object
JavaScript – Location Object ”; Previous Next Window Location Object The location object in JavaScript provides information about the browser”s location, i.e., URLs. It is a built-in property of both the window and document objects. We can access it using either window.location or document.location. The ”location” object contains various properties and methods to get and manipulate the information of the browser”s location (URL). JavaScript Location Object Properties We can use the properties of the location object to get information of URL: hash − This property is used to set or get the anchor part of the URL. host − This property is used to set or get the hostname or port number of the URL. hostname − This property is used to set the hostname. href − This property is used to set or get the URL of the current window. origin − This property returns the protocol, domain, and port of the URL. pathname − This property updates or gets the path name. port − This property updates or gets the port of the URL. protocol − This property updates or gets the protocol. search − This property is used to set or get the query string of the URL. Syntax Follow the syntax below to access the location object”s properties and methods − window.location.property; OR location.property; You may use the ”window” object to access the ”location” object. Here, we have demonstrated the use of some properties of the location object with examples. Example: Accessing location host property The location.host property returns the host from the current URL. However, you can also change the host using it. In the below code, we extract the host from the URL. You can see that it returns ”www.tutorialspoint.com”. <html> <body> <div id=”output”></div> <script> const host = location.host; document.getElementById(“output”).innerHTML = “The host of the current location is: ” + host; </script> </body> </html> Output The host of the current location is: www.tutorialspoint.com Example: Accessing location protocol property The location.protocol propery is used to get used in the current URL. You can also use it to update the protocol. Try the following example to use the location.protocol property – <html> <body> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “The protocol of the current location is: ” + location.protocol; </script> </body> </html> Output The protocol of the current location is: https: Example: Accessing location hostname property The location.hostname property returns the host name of the current URL. You can use it to the hostname as well. Try the following example to use location.hostname property – <html> <body> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “The host name of the current location is: ” + location.hostname; </script> </body> </html> Output The host name of the current location is: www.tutorialspoint.com Example: Accessing location pathname property The location.pathname property returns the path name of the current location. You can set the path name using it. <html> <body> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “The protocol of the current location is: ” + location.pathname; </script> </body> </html> Output The protocol of the current location is: /javascript/javascript_location_object.htm JavaScript Location Object Methods We can also use the methods of the location object to navigation to new URLs − assign(url) − This method loads a new document at the specified URL. replace(url) − This method replaces the current document with a new document at the specified URL. reload() − This method reloads the current document. JavaScript location assign() method The location.assign() method takes the URL and changes the URL in the current window. In short, it opens a new web page. Syntax Follow the syntax below to use the location.assign() method in JavaScript − location.assign(); Example In the below code, when you click the ”Go to home page” button, it will redirect you to the home page of the tutorialpoint website. <html> <body> <div id=”output”></div> <button onclick=”changePage()”>Go to Home Page</button> <script> let output = document.getElementById(“output”); function changePage() { window.location.assign(“https://www.tutorialspoint.com/”); } </script> </body> </html> Location Object Properties List Here, we have listed all properties of the Location object. Property Description hash It is used to set or get the anchor part of the URL. host It is used to set or get the hostname or port number of the URL. hostname It is used to set the hostname. href It is used to set or get the URL of the current window. origin It returns the protocol, domain, and port of the URL. pathname To update or get the path name. port To update or get the port of the URL. protocol To update or get the protocol. search To set or get the query string of the URL. Location Object Methods List Here, we have listed all methods of the Location object. Method Description assign() To load resources at a particular URL. reload() To reload the web page. replace() To replace the resources of the current webpage with another webpage”s resources. toString() Returns the URL in the string format. Print Page Previous Next Advertisements ”;
JavaScript – Worker API
JavaScript – Worker API ”; Previous Next 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. function counter() { postMessage(data); // To send data to the main thread setTimeout(“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 = new Worker(“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; function startWorker() { if (typeof (Worker) !== “undefined”) { if (typeof workerObj === “undefined”) { workerObj = new Worker(“app.js”); workerObj.onmessage = function (event) {//Getting the message from web worker output.innerHTML += “Event data is: ” + event.data + “<br>”; }; } } else { output.innerHTML += “Web worker is not supported by your browser.”; } } function stopWorker() { // To stop the web worker. if (typeof workerObj !== “undefined”) { workerObj.terminate(); workerObj = undefined; } } </script> </body> </html> 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; function timedCount() { 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. 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 don’t 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 Print Page Previous Next Advertisements ”;
JavaScript – new Keyword
JavaScript – new Keyword ”; Previous Next The new keyword in JavaScript is used to create an instance of the object that has constructor function. Using new keyword, we can create the instances of a user-defined as well as built-in object types. We can create instances of the classes, prototype, or constructor functions. When a JavaScript function is called with new keyword, the function is used as constructor. The new keyword will do the following: Creates a blank/ empty JavaScript object. Sets its prototype for inheritance. Binds this variable internally with newly created object. Executes the constructor function using new crated object whenever this is used. Returns newly created object, unless the contractor function returns a non-null object reference. The new keyword is also used to create an instance of the built-in JavaScript objects like String, Boolean, Number, etc. Syntax The syntax to use the new keyword in JavaScript is as follows – new Constructor(arguments); Parameters Constructor − It is the name of the constructor function or class name. arguments −It can be multiple arguments to initialize the object properties with them. Return Value It returns the newly created object if the constructor function returns nothing or a primitive value. It returns the value that is returned by constructor function if constructor returns a non-primitive value. Using ”new” keyword with Function Constructor To use a function as a constructor, we should call the function with new keyword placing it before the function name. We can define multiple objects using function constructor. The function constructor works as the object”s prototype. Follow the syntax below to use the ”new” keyword and constructor function to define the object. new FuncName(arguments); Example We have defined the Watch() constructor function in the code below. The Watch() constructor function initializes the brand, price, and type properties. After that, we have created two new instances of the Watch() function and printed them in the output. <html> <body> <div id = “output”> </div> <script> function Watch(brand, price, type) { this.brand = brand; this.price = price; this.type = type; } const titan = new Watch(”titen”, 4000, ”analog”); const sonata = new Watch(”sonata”, 3000, ”digital”); document.getElementById(”output”).innerHTML += “The titan object is: ” + JSON.stringify(titan) + “<br>” + “The sonata object is: ” + JSON.stringify(sonata); </script> </body> </html> Output The titan object is: {“brand”:”titen”,”price”:4000,”type”:”analog”} The sonata object is: {“brand”:”sonata”,”price”:3000,”type”:”digital”} Example In the below code, we have defined the Laptop() constructor function, initializing various properties related to the laptop. Also, we have defined the getLaptop() function, which prints the laptop details. After that, we created the two instances of the Laptop() object and used the getLaptop() method with both. In this way, you can share single methods with different objects. <html> <body> <div id = “output”> </div> <script> const output = document.getElementById(”output”); function Laptop(brand, model, processor) { this.brand = brand; this.model = model; this.processor = processor; this.getLaptop = function () { output.innerHTML += this.brand + “, ” + this.model + “, ” + this.processor + “<br>”; } } const HP = new Laptop(”HP”, “VIKING”, “i7″); const Dell = new Laptop(”Dell”, “Inspiron”, “i5″); HP.getLaptop(); Dell.getLaptop(); </script> </body> </html> Output HP, VIKING, i7 Dell, Inspiron, i5 Using ”new” keyword with Class You can also use the new keyword to define the instance of a class. The class also provides the blueprint for the object. Before ES6, the constructor function was used to define the template for the object. After ES6, classes are used to define the template for the object. Example In the below example, we have defined the ”WindowClass class. In the ”WindowClass” we have added the constructor to initialize the properties. We have also added the getDetails() method in the class. After that, we used the ”new” keyword followed by the class name to define an object of the WindowClass. Next, we invoke the getDetails() method on the instance of the class. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”) class WindowClass { constructor(color, size, type) { this.color = color; this.size = size; this.type = type; } getDetails = function () { output.innerHTML = “Color: ” + this.color + “<br>” + “Size: ” + this.size + “<br>” + “Type: ” + this.type; } } // Creating the instance of WindowClass class const window1 = new WindowClass(”blue”, ”small”, ”wooden”); // Calling function object window1.getDetails(); </script> </body> </html> Output Color: blue Size: small Type: wooden Using ”new” keyword with built-in object You can also use the ”new” keyword to define the instance of the built-in object having constructor functions. Follow the syntax below to create an instance of the built-in object Number. const num = new Number(10); In the above syntax, we have passed the numeric value as an argument of the Number() constructor. Example In the code below, we have used the Number() and String() constructors with a new keyword to define the numeric and string objects. After that, we used the ”typeof” operator to check the type of num and str variables. In the output, you can see that the num and str variable type is an object. <html> <body> <div id = “output”> </div> <script> const num = new Number(10); const str = new String(“Hello”); document.getElementById(“output”).innerHTML = “num = ” + num + “, typeof num ” + typeof num + “<br>” + “str = ” + str + “, typeof str ” + typeof str; </script> </body> </html> Output num = 10, typeof num object str = Hello, typeof str object Print Page Previous Next Advertisements ”;
JavaScript – Event Capturing
JavaScript – Event Capturing ”; Previous Next 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. Aspect Description Phase Event capturing is the initial phase in the event propagation model. Direction Capturing occurs in the reverse order of the element hierarchy, from the root of the document tree down to the target element. Use Case Useful 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. Registration Register event listeners for the capturing phase using the third parameter of addEventListener (e.g., element.addEventListener(”click”, myFunction, true);). Propagation Automatic propagation that precedes the target and bubbling phases. The event flows down the hierarchy, triggering capturing phase handlers on each ancestor. Preventing Default Use event.preventDefault() during the capturing phase to prevent the default behavior of the event before it reaches the target. Stopping Propagation Use 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> Print Page Previous Next Advertisements ”;
JavaScript – Custom Events
JavaScript – Custom Events ”; Previous Next 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: Concept Description Custom Event The 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 Constructor The 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 Method A 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 Method A 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 Types Strings that identify the type of event. Custom events can have any user-defined string as their type. Event Handling Listening 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 Pattern In 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 Property An 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 = new Event(”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 = new CustomEvent(”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 = new Event(“TutorialEvent”); const event2 = new Event(“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. Print Page Previous Next Advertisements ”;
JavaScript – Performance
JavaScript – Performance ”; Previous Next JavaScript is very important in every website today. If JavaScript fails, our website wouldn”t work properly. It is important to focus on the performance on JavaScript as it has impacts on delivering a positive user experience, retaining engagement, and ensuring business success. An optimized JavaScript would ensure the pages load faster and responsive interactions contribute to users satisfaction and hence higher conversion rates as well as higher search engine rankings (as the SEO would be better). In a competitive digital landscape, optimized JavaScript code not only attracts and retains users but also enhances resource efficiency, reducing server costs and providing a competitive advantage. With the increasing prevalence of mobile devices and the emphasis on Progressive Web Apps, performance optimization is not only a user expectation but a strategic necessity for businesses aiming to stand out and thrive in the online space. Optimizing DOM Manipulation DOM manipulation is where each element is represented as a node in the tree and accessed or modified via their ids, class names etc. These DOM manipulation operations should be minimized as much as possible and would have a significant impact on the speed of our application. Let us consider the below example where we are dynamically creating a list of 1000 items. Example Naive Code <!DOCTYPE html> <html> <body> <ul id=”itemList”></ul> <script> const itemList = document.getElementById(”itemList”); // Inefficient DOM manipulation for (let i = 0; i < 1000; i++) { itemList.innerHTML += `<li>Item ${i}</li>`; } </script> </body> </html> Optimized Code <!DOCTYPE html> <html> <body> <ul id=”itemList”></ul> <script> // Efficient DOM manipulation using document fragment const itemList = document.getElementById(”itemList”); const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { const listItem = document.createElement(”li”); listItem.textContent = `Item ${i}`; fragment.appendChild(listItem); } itemList.appendChild(fragment); </script> </body> </html> Asynchronous Operations with Promises To prevent the main thread from blocking, we must prioritize asynchronous programming. Consider this example: data retrieval from an API using Promises; in such instances, a Promise proves indispensable for managing asynchronous data fetching. Preventing the UI from freezing during operation; enhancing the overall user experience: these are the benefits. Example <!DOCTYPE html> <html> <body> <h2>Asynchronous Operations with Promises</h1> <div id=”dataContainer”></div> <script> // Fetch data asynchronously function fetchData() { return new Promise((resolve, reject) => { // Simulating an API call with a delay setTimeout(() => { const data = { message: ”Hello, world!” }; resolve(data); }, 1000); }); } // Usage of the fetchData function fetchData() .then(data => { document.getElementById(”dataContainer”).textContent = data.message; }) .catch(error => { alert(”Error fetching data:”, error); }); </script> </body> </html> Deferred JavaScript Loading JavaScript is normally loaded when the page is opened, however by delaying the loading of JavaScript we can optimize page load performance especially when dealing with non-essential scripts. When browsers come across the <script> tag, they normally block the rendering until the script has finished downloading and executing. However, by using the defer attribute in the script tag, we can instruct the browser to continue downloading the script in the background while it continues to parse & render the HTML. The script is then executed after the HTML is completely parsed. Example <!DOCTYPE html> <html> <body> <p>Deferred JavaScript Loading</p> <script defer src=”https://code.jquery.com/jquery-3.6.4.min.js”></script> <div id=”loadingMessage”>JavaScript is loading…</div> <script> // Add an event listener to indicate when the JavaScript is fully loaded document.addEventListener(”DOMContentLoaded”, function() { document.getElementById(”loadingMessage”).textContent = ”JavaScript has finished loading!”; }); </script> </body> </html> Another option to the above code is to use the async attribute. While similar to defer, async loads the script asynchronously, but it doesn”t guarantee the order of execution. The script that finishes loading first will be executed first. Avoiding Global Variables Global variables are those which are visible throughout the code, or have a big scope. It is import to understand if our code actually requires the scope of variables to be global or can it be managed efficiently by code encapsulation. The below examples demonstrates the usage of encapsulation to avoid global variables hence leading to better performance of the script. Example <!DOCTYPE html> <html> <body> <h2>Avoiding Global Variables</h2> <div id=”result”></div> <script> var resultElement = document.getElementById(”result”); // Inefficient use of global variables var globalVar = 10; function addNumbers(x, y) { return globalVar + x + y; } resultElement.innerHTML += “Using global variable, the sum is ” + addNumbers(51, 7) + “<br>”; // Improved encapsulation (function () { var localVar = 10; function addNumbers(x, y) { return localVar + x + y; } resultElement.innerHTML += “Using encapsulation, the sum is ” + addNumbers(51, 7); })(); </script> </body> </html> While we have discussed performance optimization in this tutorial from a JavaScript point of view, it is important to note that certain optimizations remain constant irrespective of the language. This includes scenarios like using switch case instead of length if else if, memory management, concurrency, etc. The performance optimization of JavaScript has impacts across industries & applications. In ecommerce, a high speed page load has proven to enhance user engagement and boost conversation rates, while in social media JavaScript has helped in providing seamless interactions. News and media related websites benefit as the content gets updated quickly and only learning platforms (edtech industry) requires JavaScript for interactive educational components. On the other hand, financial applications, collaboration tools, gaming websites, and healthcare apps all demand optimized JavaScript to ensure their interfaces are responsive and process data in a timely manner. Print Page Previous Next Advertisements ”;
JavaScript – addEventListener() ”; Previous Next 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 element const button = document.getElementById(“myButton”); // Define the event handler function function handleClick() { alert(“Button clicked!”); } // Attach the event listener to the button button.addEventListener(“click”, handleClick); </script> </body> </html> 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; } </style> </head> <body> <div id=”myDiv”>Hover over me</div> <script> // Get the div element const myDiv = document.getElementById(“myDiv”); // Define the event handler function function handleMouseover() { myDiv.style.backgroundColor = “lightcoral”; } // Attach the event listener to the div myDiv.addEventListener(“mouseover”, handleMouseover); // Additional example: Change color back on mouseout function handleMouseout() { myDiv.style.backgroundColor = “lightblue”; } myDiv.addEventListener(“mouseout”, handleMouseout); </script> </body> </html> 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”. Print Page Previous Next Advertisements ”;