JavaScript – Multiline Strings ”; Previous Next A multiline string is a JavaScript string that spans multiple lines. Using multiline strings in programs make it easier to read and maintain. In JavaScript, the easiest way to create multiline strings is to use template literals (template strings). The template literals are introduced in ECMAScript 2015 (ES6). Before introduction of template literals, the multiline strings are created by concatenating multiple strings using + operator. In JavaScript, a string is a sequence of characters containing alphabetical, numeric, and special characters. We can create the string using single quote (”), double quote (“) or backtick (`) characters. Creating Multiline Strings Using Template Literals The template literals are the best way to create multiline string in JavaScript. Template literals are enclosed with backtick (`) characters. A template literal contains strings and also placeholders. Template literals are sometimes also called template strings. A simple example of a template literal is as follows − `This is a template literal enclosed by backtick characters.` Let”s now create a multiline string using template literals − let multilineString = `This is a multiline string created using template literal.` In the above JavaScript code snippet, we have created a multiline string containing three lines. We assigned this multiline string to the variable called multilineString. Example In the below example, we have created a multiline string using template literal and displayed the string in the web console. let mulString = `This is a multiline string created using template literal.`; console.log(mulString); Output This is a multiline string created using template literal. Example In the below example, we are trying to display the multiline string crated using the template literal on the webpage. We used <br> to make a line break. <!DOCTYPE html> <html> <body> <p id = “output”></p> <script> let mulString = `This is a multine <br> string created using template literal <br> and displayed on the webpage.`; document.getElementById(“output”).innerHTML = mulString; </script> </body> </html> Output This is a multine string created using template literal and displayed on the webpage. Creating Multiline String Using + Operator We can also create a multiline string in JavaScript by concatenating the individual strings using + operator. To create a line break, we can use the escape character n or <br>. You can concatenate the strings defined with single or double quotes. Let”s have a look at the following example − Example In this example, we created a multiline string by concatenating three individual strings. We used escape character (n) at the end of the individual strings to break the line. let mulString = “This is a multiline stringn” + “created by concatenating the individual stringsn” + “and using \n to break the line.”; console.log(mulString); Output This is a multiline string created by concatenating the individual strings and using n to break the line. Example In the example below, we created a multiline string by concatenating three strings. We used <br> to break the line. <!DOCTYPE html> <html> <body> <p id = “output”></p> <script> let mulString = “This is a multiline string <br>” + “created by concatenating the individual strings<br>” + “and line break.”; document.getElementById(“output”).innerHTML = mulString; </script> </body> </html> Output This is a multiline string created by concatenating the individual strings and line break. Creating Multiline String Using Operator We can use backslash () operator to create multiline strings in JavaScript. We can use the escape character (n) to break the line. Example Try the following JavaScript example − let mulString = “This is a multiline stringn created using the backslash operatorn and escape character to break the line.”; console.log(mulString); Output This is a multiline string created using the backslash operator and escape character to break the line. Example In the example below, we have created a multiline string using the backslash () operator. And to make a line break, we used <br>. <!DOCTYPE html> <html> <body> <p id = “output”></p> <script> let mulString = “This is first line of the multiline string <br> This is second line of the multiline string <br> This is the last line of multiline string.”; document.getElementById(“output”).innerHTML = mulString; </script> </body> </html> Output This is first line of the multiline string This is second line of the multiline string This is the last line of multiline string. Print Page Previous Next Advertisements ”;
Category: javascript
JavaScript – DOM Collections
JavaScript – DOM Collections ”; Previous Next The DOM (Document Object Model) collections are a way to group together related HTML elements. They are read-only and can be accessed using the properties of DOM objects such as the document object or a DOM node. There are many different types of DOM collections, including: The HTMLCollection object is an array-like list (collection) of HTML elements. The NodeList object is a list (collection) of nodes extracted from a document. The Form element collection in HTML DOM is used to set or return the collection of all <input> elements inside a form element. The HTML DOM forms collection is used for returning all the form elements that are present inside the HTML document as a collection. DOM collections can be used to perform a variety of tasks, such as: Traversing the DOM Adding, removing, or modifying elements Changing the style or content of elements Responding to user events This tutorial provides basic understanding of DOM collections, particularly HTMLCollection object. The other type of DOM collections are discussed in next chapters. The HTMLCollection Object An HTMLCollection object is an array-like data structure of HTML elements. When you use the getElementByTagName()method to access DOM elements, it returns an HTMLCollection object. It is the same as an array but not an array. You can traverse the HTML collection and access each HTML element through the index, but you can use the pop(), push(), etc. methods with HTML collection. The methods and properties given below return the HTML collection. getElementByTagName() method getElementByClassname() method children property Properties and Methods of HTMLCollection Object Here, we have listed the properties and methods that can be used with HTML collections. Method / Property Description length To get a count of HTML elements in the collection. item() To get elements from the specific index. namedItem() To get the HTML element using its id from the given collection. Example: Traversing the Collection Elements In the below code, we have added the list of numbers. In JavaScript, we access all <li> elements using the getElementByTagName() method, which returns the HTML collection. After that, we use the for…of loop to traverse each HTML element. The collection contains each HTML element in the object format. We used the innnerHTML property with each element of the collection to get its HTML and print it on the web page. <DOCTYPE html> <html> <body> <ul> <li> One </li> <li> Two </li> <li> Three </li> </ul> <div id = “output”> </div> <script> const output = document.getElementById(”output”); let lists = document.getElementsByTagName(”li”); for (let list of lists) { output.innerHTML += “inner HTML – ” + list.innerHTML + “<br>”; } </script> </body> </html> Example: Getting the length of the collection In the below code, we used the ”length” property of the collection to get the number of elements in the collection. <DOCTYPE html> <html> <body> <div class = “text”> JavaScript </div> <div class = “text”> HTML </div> <div class = “text”> CSS </div> <div class = “text”> CPP </div> <div id = “output”>The length of the collection is: </div> <script> const divs = document.getElementsByClassName(”text”); document.getElementById(”output”).innerHTML += ” ” + divs.length; </script> </body> </html> Example: Using the namedItem method with collection In the below code, we access all <div> elements using the getElementByClassName() method, returning the collection of <div> elements. After that, we used the namedItem() method to access the <div> element having id equal to ”JavaScript”. <DOCTYPE html> <html> <body> <div class = “text” id = “JavaScript”> JavaScript </div> <div class = “text” id = “PHP”> PHP </div> <div class = “text” id = “Python”> Python </div> <div class = “text” id = “Java”> Java </div> <div id = “output”>The Element having id equal to JavaScript is: </div> <script> const output = document.getElementById(”output”); const langs = document.getElementsByClassName(”text”); output.innerHTML += langs.namedItem(”JavaScript”).innerHTML; </script> </body> </html> Collections of document Object and DOM Elements The document object contains some built-in collection to get the elements from the document. In the below table, we have listed all collections which can be accessed using the document object. Collection Name Description document.links To get all <a> elements from the document. document.forms To get all <form> elements from the document. document.images To get all <img> elements from the document. document.scripts To get all <script> elements from the document. document.styleSheets To get all the document”s <link> and <style> elements. Element.children To get a collection of all children of the particular HTML element. element.attributes To get the collection of all attributes of the given element. element.options To get all <options> elements from the document. element.classList To get a collection of class names of a particular DOM element. Print Page Previous Next Advertisements ”;
JavaScript – Event Delegation ”; Previous Next Event delegation in JavaScript is a technique that allows us to attach a single event listener to a parent element, and then use the event object to determine which child element triggered the event. This way, we can handle multiple events with a single event listener, and avoid adding too many event listeners to the DOM. Steps of Event Delegation 1. Attach a Listener to a Common Ancestor Attach a single event listener to a parent element, encapsulating the elements you wish to monitor; this is in lieu of attaching individual event listeners for each element. Use methods such as addEventListener for efficient implementation. 2. Check the Target Element Inspect the event.target property within the event handler to pinpoint the specific element that triggered it in its common ancestor. Common checks involve scrutinizing tagName, classList, or other target element properties. 3. Perform the Desired Action Based on the identified target element and any specified criteria, execute the desired action or functionality. This could involve modifying content, handling a button click, or performing any custom logic associated with the event. Event Delegation Examples Example: List Item Clicks In this example, we employ event delegation to adeptly manage clicks on a dynamically changing list of tutorials. The <ul> element serving as the shared ancestor for all list items has one solitary event listener attached to it. Upon clicking a tutorial, an <li> identifies itself as the target via our skilfully crafted event handler; consequently, enabling logging of that particular tutorial”s content in the console. This demonstrates the streamlined and scalable approach of event delegation in managing dynamic lists. <!DOCTYPE html> <html> <head> <style> ul {list-style-type: none; padding: 0;} li {margin: 5px; padding: 10px; border: 1px solid #ccc; cursor: pointer; max-width: 30%; } </style> </head> <body> <ul id=”myList”> <li>Tutorial 1</li> <li>Tutorial 2</li> <li>Tutorial 3</li> <li>Tutorial 4</li> <li>Tutorial 5</li> </ul> <div id = “output”></div> <script> const output = document.getElementById(“output”); const myList = document.getElementById(“myList”) myList.addEventListener(“click”, function(event) { if (event.target.tagName === “LI”) { output.innerHTML += “Tutorial clicked: ” + event.target.textContent + “<br>”; } }); </script> </body> </html> Example: Form Control Changes Employing event delegation here allows for the monitoring and logging of changes in form control values: the <form> element acts as a common ancestor, while an input event listener captures alterations within input fields. The script confirms by examining the target element within its handler, that events are indeed related to an <input>. The message, consequently, logs the modified input”s name and new value: this action not only showcases event delegation”s adaptability but also its efficiency in managing dynamic form interactions. <!DOCTYPE html> <html> <body> <form id=”myForm”> <input type=”text” name=”username” placeholder=”Username”> <input type=”password” name=”password” placeholder=”Password”> <button type=”button”>Submit</button> </form> <div id=”message”></div> <script> const messageElement = document.getElementById(“message”); const myForm = document.getElementById(“myForm”) myForm.addEventListener(“input”, function(event) { if (event.target.nodeName === “INPUT”) { messageElement.innerHTML += “Input changed: ” + event.target.name + ” – New value: ” + event.target.value+”<br>”; } }); </script> </body> </html> Event delegation is valuable in scenarios where a single event listener can efficiently manage interactions for multiple elements, reducing redundancy and improving performance. Common use cases include handling dynamic lists, form interactions, table actions, accordion or tabbed interfaces, tree structures, dropdown menus, multi-step wizards, carousels, and various interactive UI components. It simplifies code structure, ensures consistency, and adapts well to dynamic content changes, making it a versatile technique in web development. Print Page Previous Next Advertisements ”;
JavaScript – IndexedDB
JavaScript – IndexedDB ”; Previous Next What is IndexedDB? IndexedDB, or Indexed Database, represents a low-level JavaScript API. Its function involves the storage and retrieval of voluminous structured data – this includes files and blobs. With its capabilities to work with client-side databases: it enables web applications to locally store, query, and modify data on the user”s device. This functionality proves particularly advantageous when constructing web applications that confront significant data volumes; operate without an internet connection, working offline and deliver responsive user experiences through local data caching. Key concepts and features of IndexedDB: Asynchronous API − Relying on event-driven programming, IndexedDB utilizes an asynchronous API to prevent main-thread blocking and enhance user experience. Database − IndexedDB databases, functioning as containers for object stores, facilitate the organization, retrieval and deletion of data. Object Store − An object store akin to a table in a relational database, encapsulates collections of JavaScript objects; it provides support for CRUD operations. Index − Indexes in object stores can enhance the efficiency of data querying, as they are able to improve search and sort performance based on specific fields. Transactions − Transactions in IndexedDB perform all operations, guaranteeing consistency and integrity through their ability to make multiple actions either succeed or fail as a unit. Why use IndexedDB? Web developers, in their search for efficient client-side storage solutions, find IndexedDB indispensable. Its asynchronous nature guarantees a responsive user experience: it thwarts main-thread blocking; moreover, its support for transactions by maintaining data integrity is commendable. IndexedDB is capable of managing significant volumes of structured data locally; this capability significantly enhances offline functionality a reduction on the need for relentless server communication. With its flexible key structure, indexing support for optimized queries, and the ability to upgrade schema; it stands as a robust choice for constructing web applications. These applications often require local storage, offline support and most importantly effective data management. CRUD Operations Let us now see the CRUD operation codes with IndexedDB. Create/Insert Operation To insert a new record into an object store, you utilize the add() method in IndexedDB. This method accepts a JavaScript object or value as its parameter and subsequently incorporates it within the designated object store. However, if there already exists an entry with identical key parameters; this operation will fail, thus rendering it ideal for guaranteeing uniqueness. const request = objectStore.add(data); request.onsuccess = () => { // Handle success event }; request.onerror = () => { // Handle error }; Read (Retrieve) Opeation The get() Method Utilize the get() method: it retrieves a singular record from an object store, this action is contingent upon your possession of knowledge regarding the specific key for your intended entry. The openCursor() Method Initiating an active cursor that iterates through records within an object store, the openCursor() method enhances efficiency and control by allowing for processing each individual entry; this proves useful in traversing all entries present in the said object store. const request = objectStore.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const data = cursor.value; // Process data cursor.continue(); } }; request.onerror = () => { // Handle error }; Update Operation The put() method updates an existing record or adds a new one when the key doesn”t exist. Its versatility renders it suitable for data manipulation, specifically updating and inserting. const request = objectStore.put(data); Delete Operation To remove a specific record from an object store based on its key, one must employ the delete() method; this method offers a direct approach for deleting entries. const request = objectStore.delete(key); Implementation Example All the important methods of the above CRUD operation are implemented in this code. It presents database data as a table, each record accompanied by delete and update buttons. When you click on the create button, it displays an element for form creation on screen; thereby allowing entry of name and email to be inserted into the database. By default, this form remains hidden; it only appears upon button click and subsequently vanishes when its task is complete. The ”prompt()” method populates the details update form, a feature that provides convenience for users as alerts also appear in this same location. Moreover: pertinent alerts serve to signal either successful events or errors to the user. <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; margin: 20px; } h2 { color: #333; } button { padding: 8px; margin: 5px; } #createForm, #updateForm { display: none; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; } table { border-collapse: collapse; width: 100%; margin-top: 20px; width: auto; } th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; } th { background-color: #f2f2f2; } </style> </head> <body> <h2>IndexedDB CRUD Operations</h2> <button onclick=”showCreateForm()”>Create Data</button> <div id=”createForm” style=”display: none;”> // hidden by default, displayed on create button click <h3>Create Data</h3> <label for=”name”>Name:</label> <input type=”text” id=”name” required><br><br> <label for=”email”>Email:</label> <input type=”email” id=”email” required><br> <button onclick=”createData()”>Save</button> <button onclick=”cancelCreate()”>Cancel</button> </div> <table id=”data-table”> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody></tbody> </table> <script> const dbName = “myDatabase”; let db; // Open/create indexedDB named myDatabase with version 11 const request = window.indexedDB.open(dbName, 11); request.onerror = (event) => { alert(“Database error: ” + event.target.errorCode); }; request.onsuccess = (event) => { db = event.target.result; showData(); }; request.onupgradeneeded = (event) => { db = event.target.result; const objectStore = db.createObjectStore(“myObjectStore”, { keyPath: “id”, autoIncrement: true }); objectStore.createIndex(“name”, “name”, { unique: false }); objectStore.createIndex(“email”, “email”, { unique: true }); }; function showData() { //populates the table from the db const transaction = db.transaction([“myObjectStore”], “readonly”); const objectStore = transaction.objectStore(“myObjectStore”); const tableBody = document.querySelector(“#data-table tbody”); tableBody.innerHTML = “”; const request = objectStore.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const row = tableBody.insertRow(); row.insertCell(0).textContent =
JavaScript – Debugging
JavaScript – Debugging ”; Previous Next What is Debugging? Debugging in JavaScript is a process of examining JavaScript code and finding erros and fixing them. Every now and then, developers commit mistakes while coding. This error can be logical, syntax, or runtime errors. An error in a program or a script is referred to as a bug. The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks. Let”s look at the different methods of debugging. Use a JavaScript Debugger A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution. Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values. Nowadays, all modern browser comes with built-in debuggers. You can use the console of the browser to debug the JavaScript code. How to Open Console in the Browser? In this section, you will learn to open the console in different browsers. Open Console in Chrome Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open Chrome web browser and open the web page in a new window. Step 2 − Right-click anywhere on the web page. Step 3 − It will pop up menu. Select the last option, which is ”inspect”. Step 4 − It will open a Chrome developer tool. Step 5 − Go to the console tab. Open Console in Firefox Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open Firefox web browser and open the web page in a new window. Step 2 − Right-click anywhere on the web page. Step 3 − Select the last option from the popup menu, which is ”inspect(Q)”. Step 4 − It will open a developer tool. Step 5 − You can move from the ”inspector” tab to the ”console” tab. Open Console in Microsoft Edge Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open the Microsoft Edge browser. Step 2 − Right-click anywhere on the web page. Step 3 − Click on ”inspect” in the popup menu. Step 4 − You will see the developer tool is opened. Step 5 − Next, you can change the ”Elements” tab to the ”Console” tab in the developer tool. Open Console in Safari Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open the Safari web browser. Step 2 − Open the Safari main menu from the top menu bar. Step 3 − Choose ”preferences” in the dropdown menu. Next, choose the ”advanced” option. Step 4 − Check the checkbox named ”Enable Show Develop menu in menu bar” to enable the developer tool. Next, close the preference window. Step 5 − Next, reopen the main menu and select ”Develop’. After that, select the ”Show Error Console’. Open Console in Opera Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open the Opera browser. Step 2 − Open the main menu from the top corner. Step 3 − In the main menu, select the ”Developer’. It will open the sub-menu. Step 4 − In the submenu, select the ”developer tools’. Step 5 − Next, select the ”console’. It will open a console. Using the console.log() method The console.log() method prints the message in the web browser”s console. It can print primitive values, objects, variable values, etc. You can print the variable”s value in the console you want to debug. Syntax Users can follow the syntax below to use the console.log() method. Console.log(val1, val2, …); The console.log() method takes the comma-separated arguments to print in the web browser”s console. Example In the code below, we add the value of the num1 and num2 variables. In the browser, you can see that the sum is 32 rather than 5. So, you are required to debug the code. When you print the type of the num1 and num2 into the console, it shows that the type of the num1 is a string. So, it converts the value of the num2 variable into the string and appends it with the value of the num1. <html> <body> <div id = “output”> </div> <p>Note: To see the resullt in console, please open it before you run
JavaScript – Ajax
JavaScript – Ajax ”; Previous Next Asynchronous JavaScript and XML (Ajax) represents a web development technique: it enables dynamic, interactive communication between server and webpage without necessitating complete page reload. The descriptor “asynchronous” underlines that data exchanges can occur in the background, independent of user experience disruption. Rather than idly awaiting full-page refreshment; Ajax empowers real-time updates on specific sections of a webpage, thus yielding an interface that is more seamless and responsive. How Ajax works? The central role in enabling dynamic updates, without the necessity of a full page reload, belongs to the XMLHttpRequest object within JavaScript”s Ajax functionality. This particular process allows for asynchronous communication between server and web page. The server responds with data, usually in JSON or XML format when receiving a request sent by this object. Processing this data is the task of JavaScript; it updates specific portions of the webpage in real-time. The asynchronous nature which is a critical feature for modern web development ensures these operations occur unobtrusively in background, thereby enhancing interactivity by allowing data to be fetched and sent asynchronously. Here, we will to explore Ajax to get a deeper understanding of it. There are 4 approaches to make Ajax calls or to implement Ajax in JavaScript and they are: XMLHttpRequest (Older Approach) Fetch API (Modern Approach) Axios (Library for HTTP Requests) jQuery Ajax We will be using JSONPlaceholder in all the examples for understanding purposes. JSONPlaceholder is an open-source and simulated REST API provider which lets developers test their prototype applications. It returns fake/dummy data for various resources like users, posts, comments etc. The API endpoints of JSONPlaceholder can be made using HTTP requests and they will be mimicking the nature of real APIs without any need for authentication. Our goal here is to use these APIs/endpoints to under Javascript-Ajax. Using XMLHttpRequest The Native JavaScript approach using XMLHttpRequest represents the oldest method for asynchronous requests. It relies on the XMLHttpRequest object to create and send HTTP requests. This method involves setting up callback functions to handle various states of the request, making it suitable for simpler scenarios. However, it has some limitations compared to more modern approaches. Example <!DOCTYPE html> <html lang=”en”> <body> <p>Native XMLHttpRequest Example</p> <button onclick=”nativeAjax()”>Make Request</button> <pre id=”result”></pre> <script> function nativeAjax() { var xhr = new XMLHttpRequest(); xhr.open(”GET”, ”https://jsonplaceholder.typicode.com/users/2”, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var responseData = JSON.stringify(JSON.parse(xhr.responseText), null, 2); document.getElementById(”result”).innerText = ”Native XMLHttpRequest:n” + responseData; } }; xhr.send(); } </script> </body> </html> Using Fetch API Presenting a modern alternative to XMLHttpRequest, the Fetch API offers a more straightforward and powerful syntax; it returns Promises thus enhancing the intuitive handling of asynchronous operations. Supporting an extensive array of HTTP methods and headers: this provides developers with a cleaner, concise method for making asynchronous requests. Contemporary JavaScript applications often prefer it for its clarity and ease of use. Example <!DOCTYPE html> <html> <body> <h1>Fetch API Example</h1> <button onclick=”fetchApi()”>Make Request</button> <pre id=”result”></pre> <script> function fetchApi() { fetch(”https://jsonplaceholder.typicode.com/users/3”) .then(response => { if (!response.ok) { throw new Error(”Network response was not ok”); } return response.json(); }) .then(data => { var formattedData = JSON.stringify(data, null, 2); document.getElementById(”result”).innerText = ”Fetch API:n” + formattedData; }) .catch(error => { document.getElementById(”result”).innerText = ”Fetch API Error: ” + error.message; }); } </script> </body> </html> Using Axios Designed for making HTTP requests, Axios emerges as a popular JavaScript library. Its popularity is largely due to its clean and concise syntax: built on Promises; furthermore, it boasts automatic JSON data transformation support features that set it apart from other libraries in the field. Offering more than just basic functionality, Axios presents advanced features such as request and response interceptors, a robust selection for managing AJAX operations within the context of modern web development environment. Example <!DOCTYPE html> <html> <head> <script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js”></script> </head> <body> <h1>Axios Example</h1> <button onclick=”axiosExample()”>Make Request</button> <pre id=”result3″></pre> <script> function axiosExample() { axios.get(”https://jsonplaceholder.typicode.com/users/5”) .then(response => { var formattedData = JSON.stringify(response.data, null, 2); document.getElementById(”result3”).innerText = ”Axios:n” + formattedData; }) .catch(error => { document.getElementById(”result3”).innerText = ”Axios Error: ” + error.message; }); } </script> </body> </html> Using Ajax jQuery The $.ajax method in jQuery simplifies the AJAX request process: a popular approach previously; however, its usage has waned alongside modern JavaScript”s ascent. Offering an interface that is both consistent and cross-browser compatible, jQuery Ajax remains suitable for projects already using or needing specific features of jQuery due to these advantages it presents. However, for new projects, modern alternatives may be preferred. Example <!DOCTYPE html> <html> <head> <script src=”https://code.jquery.com/jquery-3.6.4.min.js”></script> </head> <body> <h1>jQuery Ajax Example</h1> <button onclick=”jqueryAjax()”>Make Request</button> <pre id=”result4″></pre> <script> function jqueryAjax() { $.ajax({ url: ”https://jsonplaceholder.typicode.com/users/7”, method: ”GET”, dataType: ”json”, success: function (data) { var formattedData = JSON.stringify(data, null, 2); document.getElementById(”result4”).innerText = ”jQuery Ajax:n” + formattedData; }, error: function (xhr, status, error) { document.getElementById(”result4”).innerText = ”jQuery Ajax Error: ” + error; } }); } </script> </body> </html> Ajax Use Cases In real-world scenarios, developers commonly employ Ajax to create web applications that are both responsive and interactive. A pertinent example: a social media platform; here, users have the ability – thanks to Ajax, to add or load new comments in the background without needing an entire page refresh. Dynamic updating ensures a user experience that is smooth and uninterrupted, permitting individuals to engage with content and one another seamlessly. This process yields a platform more responsive and engaging; it amplifies user interaction thus enhancing satisfaction. Prominent companies utilizing Ajax for enhanced user experiences include Google (Gmail, Maps), Facebook, Twitter, Amazon, Netflix, GitHub, LinkedIn, YouTube, Microsoft Office Online, and Uber. Ajax is employed for real-time updates, dynamic content loading, and seamless interactions on their respective platforms. Print Page Previous Next Advertisements ”;
JavaScript – Style Guide
JavaScript – Style Guide ”; Previous Next A JavaScript style guide is a set of general rules that regulate how to write JavaScript code. These rules can include − which quotes to use, how many spaces to indent, the maximum line length, using single-line comments, marked with //, etc. When any company starts developing a real-time JavaScript project, 100”s of developers work on that. If each developer follows a different style of writing code, it becomes very hard to manage complex code. So, it is important to follow the same code style throughout the project. Here, we have covered some essential coding conventions to follow while developing the project. Code Indentation You should always intend your code with fixed spaces (either 2, 3 or 4 spaces) according to the coding convention of your project. Also, the code should not contain trailing white spaces. Example In the code below, we have used the three spaces indentation in the function. <html> <body> <h2> Intendation Conventions </h2> <div id = “output”> </div> <script> const output = document.getElementById(”output”); function func() { output.innerHTML = “Function executed!”; return 10; } func(); </script> </body> </html> Comments You should always use the line comments rather than the block comments, and line comments should start with the left part of the code. Example In the code below, we used the ‘//’ line comments to comment the code. <html> <body> <h2> Comment Conventions </h2> <div id=”output”> </div> <script> const output = document.getElementById(”output”); output.innerHTML = “Hello World!”; // var a = 10; // var b = 20; </script> </body> </html> Variable Declaration Always declare the variable at the top of its scope. If a variable is a global variable, declare it at the top of the file. Similarly, if the variable is in th block or function, declare it at the top of the block or function. Furthermore, variable names must start with the letter. Example In the code below, we have declared the variable at the top of the code, and the name of each variable starts with a letter. <html> <body> <h2> Variable Conventions </h2> <div id=”output”> </div> <script> var a = 10; var b = 20; document.getElementById(”output”).innerHTML = “The sum of 10 and 20 is: ” + (a + b); </script> </body> </html> Identifier Names in camelCase In JavaScript, always use the camelCase convention to define the identifier. In the camelCase convention, the first letter of the identifier should be lowercase, and the first letter of the 2nd word should be in the uppercase. Here, identifiers include function names, variable names, object names, class names, etc. Example In the code below, ”greetMessage” and ”executeGreet” both identifiers are in the camelCase. <html> <body> <h2> camelCase Conventions </h2> <div id=”output”> </div> <script> var greetMessage = “Hello Developers!”; let output = document.getElementById(”output”); // Function name with camelCase function executeGreet() { output.innerHTML = greetMessage; } executeGreet(); </script> </body> </html> Spaces, and Brackets In JavaScript, we should include white space before and after each operator like ‘+’, ”typeof’, etc. Furthermore, it is also vital to include white space around brackets. Example In the code below, we added proper space after the ”if” condition. Also, we added white space before and after ‘+=’ operator. <html> <body> <h2> Space and all brackets Conventions </h2> <div id=”output”> </div> <script> let output = document.getElementById(”output”); if (9 > 10) { output.innerHTML += “9 is greater than 10”; } else { output.innerHTML += “9 is not greater than 10″; } </script> </body> </html> Object Rules In JavaScript, we use the ‘=’ assignment operator and open bracket ‘{‘ after the object identifier. Next, we write the object properties (key-value pairs separated by semicolon), and we write each property in the new line and separate them with a comma (,). Also, we don”t put a comma after the last object property. At the end, we add a semicolon (;) after adding a closing bracket. Example In the code below, we have defined the object according to the object guidelines. Also, we have shown objects on the web page using the JSON.stringify() method. <html> <body> <h2> Object Conventions </h2> <div id=”output”> </div> <script> const obj = { prop1: ”value1”, prop2: ”value2”, prop3: ”value3” }; document.getElementById(“output”).innerHTML = JSON.stringify(obj, null, 2); </script> </body> </html> Statement Rules There are 3 types of statements in JavaScript. Simple one-line statement Compound statement Multi-line statement The simple one-line statement should always end with a semicolon. For the compound statement, we put white space and an open bracket after a statement in the same line. Next, we start adding the statement body from the next line, and in the last line, we add a closing bracket. We don”t put a semicolon after the closing bracket. If the statement is too long and can”t be written in a single line, we can add a line break after the operator. Example In the code below, we have defined single one-line, compound, and multi-line statements. <html> <body> <h2> Statement Guidelines Conventions </h2> <div id=”output”> </div> <script> const output = document.getElementById(”output”); // single line statement const arr = [“one”, “two”, “Three”]; // Compound statement for (let i = 0; i < arr.length; i++) { output.innerHTML += arr[i] + “<br>”; } // Multi-line statement if (10 > 9 && 10 > 5 && 10 > 6) { output.innerHTML += “10 is greater than 9 and 10 is greater than 5 <br>”; } </script> </body> </html> Line Length It is always hard to read long lines of code. So, we should put a maximum 80 characters in a single line. Example In the code below, we have added half a string in a new line as it contains more
JavaScript – Canvas
JavaScript – Canvas ”; Previous Next Handling Canvas with JavaScript The HTML <canvas> element can be used to create and draw graphics on the web page. It can draw various graphics or shapes, like lines, circles, etc., on the web page and animate them. You can define <canvas> element in HTML, and after that, you need to use JavaScript to draw graphics on the web page. Let”s look at the syntaxes to define a canvas element in HTML and manipulate with JavaScript. Syntax Use the following syntax to create an HTML canvas element. <canvas id=”myCanvas” width=”480″ height=”320″> Your browser does not support the HTML canvas tag. </canvas> In the above syntax, we have defined the HTML <canvas> element with id as ”myCanvas”. The message written in between <canvas> tags will be displayed when the browser doesn”t support the <canvas> element. We access the canvas element using the getElementById() method of document object. Look at below syntax − var canvas = document.getElementById(”canvas_id”); var ctx = canvas.getContext(”2d”); In JavaScript, we can use the getContext(”2d”) method to get the context of the 2D canvas. Next, we can use various methods to draw a shape and fill in the color by taking the ”ctx” variable as a reference. Examples Example: Drawing a rectangle In the code below, we have added the <canvas> element in HTML. In JavaScript, we have used the getContext(”2d”) method to access the context of the canvas. After that, we used the fillstyle() method to color the element in the canvas. The fillRect() method is used to draw a rectangle. It takes the coordinates of 4 corners in the canvas. <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing Rectangle on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var canvas = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = canvas.getContext(“2d”); // Drawing rectangle using canvas ctx.fillStyle = “#FF0000”; ctx.fillRect(50,30, 470, 240); </script> </body> </html> Example: Drawing a circle In the code below, we used the arc() method to draw a circle. It takes the coordinates for the circle position as the first 2 parameters and the radius of the circle as a third parameter. <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing circle on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var c = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = c.getContext(“2d”); // Drawing circle using canvas ctx.beginPath(); ctx.arc(300, 150, 100, 0, 2 * Math.PI); ctx.stroke(); ctx.fillStyle = “green”; ctx.fill(); </script> </body> </html> Example: Drawing a lines In the code below, we have drawn the lines using the moveTo() and lineTo() methods. The moveTo() method takes the starting point of the line as a parameter, and the lineTo() method takes the ending point of the line as a parameter. <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing lines on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var canvas = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = canvas.getContext(“2d”); // Drawing lines using canvas ctx.moveTo(0, 0); ctx.lineTo(300, 200); ctx.stroke(); ctx.moveTo(300, 200); ctx.lineTo(400, 0); ctx.stroke(); </script> </body> </html> Example: Drawing a Linear gradient <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing linear gradient on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var canvas = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = canvas.getContext(“2d”); // Drawing a linear gradient ctx.beginPath(); var grd = ctx.createLinearGradient(0, 0, 440, 0); grd.addColorStop(0, “yellow”); grd.addColorStop(1, “white”); ctx.fillStyle = grd; ctx.fillRect(10, 10, 550, 240); ctx.fill(); ctx.closePath(); </script> </body> </html> Example: Text Rendering In the below example, we have rendered a text message “Hello” on the canvas. For this, we have used fillText() method. The fillText() method in HTML Canvas draws a text string on a canvas element. <html> <body> <h2> JavaScript – Canvas </h2> <p> Rendering text on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “200” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> const canvas = document.getElementById(”myCanvas”); // Getting the 2D context of the canvas const ctx = canvas.getContext(”2d”); ctx.font = ”30px Arial”; ctx.fillStyle = ”red”; ctx.fillText(”Hello, Canvas!”, 150, 100); </script> </body> </html> We have learned to use <canvas> elements in HTML and draw graphics by accessing elements using JavaScript. We can draw various shapes and add colors to shapes. Print Page Previous Next Advertisements ”;
JavaScript – Mouse Events
JavaScript – Mouse Events ”; Previous Next 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 Event Description Click When an element experiences the press of a mouse button, it triggers the click event. Double Click The dblclick event fires upon the rapid double-clicking of a mouse button. Mouse Down and Mouse Up The initiation of a mouse click triggers the ”mousedown” event, while the completion of that click causes the ”mouseup” event to occur. Mouse Move When 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 Menu When 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. Wheel When the mouse wheel rotates, it fires the ”wheel event”; this particular event commonly manifests in implementing features, notably zooming or scrolling. Drag and Drop Events 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) + “<br>”; }); </script> </body> </html> 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) + “<br>”; }); </script> </body> </html> 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 in this DIV. </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) + “<br>”; }); mouseUpDownDiv.addEventListener(”mouseup”, function(event) { outputDiv.innerHTML += ”Mouse button up!” + JSON.stringify(event) + “<br>”; }); </script> </body> </html> 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 this DIV.</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) + “<br>”; }); </script> </body> </html> 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 this DIV 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 + “<br>”; }); </script> </body> </html> Print Page Previous Next Advertisements ”;
JavaScript – DOM Forms
JavaScript – DOM Forms ”; Previous Next The DOM Forms The HTML DOM document forms are used to get the data from the users. In JavaScript, you can use the ”forms” collection of the ”document” object to access all <form> elements of the HTML document. You can access all forms elements of particular forms and manipulate them. Using JavaScript, you can validate the form values, handle the form data submission, etc. Syntax Follow the syntax below to use the ”forms” collection to manipulate the forms of the DOM. document.forms; Here, ”forms” is a property of the ”document” object. Properties of ”forms” Collection Property Description length It represents the number of <form> elements in the HTML document. Methods of ”forms” Collection Method Description [index] To get the particular <form> element from the 0-based index of the collection of HTML forms. item(index) To get the particular <form> element from the 0-based index of the collection of HTML forms. namedItem(id) To get the <form> element with a particular id. Return value The document.forms returns the collection of all forms in the same order as they are present in the HTML document. Example: Finding total <form> elements in the HTML document) In the below code, we use the ”length” property of the ”forms” collection to find the number of existing forms in the HTML document. <html> <body> <form> <input type = “text” name = “first” id = “first” value = “First Name”> </form> <form> <input type = “text” name = “second” id = “second” value = “Last Name”> </form> <form> <input type = “text” name = “third” id = “third” value = “Contact”> </form> <div id = “output”>Total number of forms in the HTML document is: </div> <script> document.getElementById(”output”).innerHTML += document.forms.length; </script> </body> </html> Example: Get the id of all <form> elements In the below code, we access each form using its index and use the ”id” property to get the id of a particular form. <html> <body> <form id = “form1”> <label for = “first”> Fruit Name: </label> <input type = “text” name = “first” id = “first”> </form> <form id = “form2”> <label for = “second”> Price: </label> <input type = “text” name = “second” id = “second”> </form> <form id = “form3”> <label for = “third”> Color: </label> <input type = “text” name = “third” id = “third”> </form> <div id = “output”> </div> <script> document.getElementById(”output”).innerHTML = “Id of the first form is: ” + document.forms[0].id + “<br>” + “Id of the second form is: ” + document.forms[1].id + “<br>” + “Id of the third form is: ” + document.forms[2].id; </script> </body> </html> Example: Get particular form using its id and namedItem() method In the code below, we used the namedItem() method by taking the ”forms” collection as a reference to get a form with a particular id. <html> <body> <form id = “form1”> <label for = “first”> First Name </label> <input type = “text” name = “first” id = “first”> </form> <form id = “form2”> <label for = “second”> Last Name </label> <input type = “text” name = “second” id = “second”> </form> <div id = “output”>The innerHTML of the form element having id equal to form2 is: </div> <script> const output = document.getElementById(”output”); output.innerHTML += document.forms.namedItem(”form2”).innerHTML; </script> </body> </html> JavaScript Form Submission In JavaScript, you can submit the form using the ”submit” input type and execute a particular function to handle the form data using the onsubmit() event handler. Example In the below code, the form takes users” first and last names. After that, when users click the submit input, it calls the submitForm() function. In the submitForm() function, we used the preventDefault() method to prevent the execution of the function without submitting the form. After that, we use the ”forms” collection to access the form and values of its input fields. At last, we print the input values in the output. <html> <body> <form onsubmit = “submitForm(event)” id = “nameform”> <p><label>First Name: </label><input type = “text” name = “firstname”></p> <p><label>Last Name: </label><input type = “text” name = “lastname”></p> <p><input type = “submit”></p> </form> <div id = “output”> </div> <script> function submitForm(e) { e.preventDefault(); const output = document.getElementById(”output”); const firstname = document.forms[”nameform”][”firstname”].value; const lastname = document.forms[”nameform”][”lastname”].value; output.innerHTML = “First Name: ” + firstname + “, Last Name: ” + lastname; } </script> </body> </html> JavaScript Form Validation In JavaScript, you can also validate the form to ensure the users have filled the required inputs. You can perform the validation check in the function that you are invoking on form submit. Furthermore, you may also show the error message in the output if the form is not fulfilling the particular condition. Example In the below code, we check whether the length of the first name and last name is less than 3 when users submit the form. If the length of firstname or lastname is less than 3, we show the error message. <html> <body> <form onsubmit = “submitForm(event)” id = “nameform”> <p>First Name: <input type = “text” name = “firstname”> </p> <p>Last Name: <input type = “text” name = “lastname”> </p> <p><input type = “submit”></p> </form> <div id = “output”> </div> <script> function submitForm(e) { e.preventDefault(); const output = document.getElementById(”output”); const firstname = document.forms[”nameform”][”firstname”].value; const lastname = document.forms[”nameform”][”lastname”].value; if (firstname.length < 3 || lastname.length < 3) { output.innerHTML += “The length of the first name or last name should be greater than 3. <br>”; } else { output.innerHTML = “First Name: ” + firstname + “, Last Name: ” + lastname; } } </script> </body> </html> JavaScript Form Data Validation It is also required to validate the input data. Sometimes, it happens that you want users to pass the numeric data, but they pass the string data by mistake. In such cases, developers are required to validate the data and show the error message. You may validate the data on the client side or server side. It is a best practice to validate the data on the client side and send pure data to the