JavaScript – Screen Object

JavaScript – Screen Object ”; Previous Next Window Screen Object The screen object in JavaScript is a property of the ”window” object. The ”screen” object”s properties contain information about the device”s screen. The screen object can be accessed by using the window.screen syntax. We can also access it without using the window object. Screen Object Properties The screen object has a number of properties that provide information about the screen”s orientation, resolution, and more. These properties can be used to develop applications that are responsive to different screen sizes and orientations. Following are some properties of the JavaScript screen object − width − The width of the screen in pixels. height − The height of the screen in pixels. availWidth − The width of the screen, minus the width of the window taskbar. availHeight − The height of the screen, minus the height of the window taskbar. colorDepth − The number of bits per pixel that the screen can display. pixelDepth − The number of bits per pixel that the screen is actually using. Screen Object Property Syntax Follow the syntax below to use the property of the screen object in JavaScript − window.screen.property; OR screen.property; You may or may not use the ”window” object to access the screen object. Example In the example below, we access the various properties of the screen object with referencing the screen as the property of window object. <html> <body> <p> Screen Information </p> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “screen height: ” + window.screen.height + “<br>” + “screen width: ” + window.screen.width + “<br>” + “screen colorDepth: ” + window.screen.colorDepth + “<br>” + “screen pixelDepth: ” + window.screen.pixelDepth + “<br>” + “screen availHeight: ” + window.screen.availHeight + “<br>” + “screen availWidth: ” + window.screen.availWidth; </script> </body> </html> Output Screen Information screen height: 864 screen width: 1536 screen colorDepth: 24 screen pixelDepth: 24 screen availHeight: 816 screen availWidth: 1536 Example In the below code, we access the various properties of the screen object and observe their value. In this example we are not referencing the window object to access the screen object. <html> <body> <p> Screen Information </p> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “screen height: ” + screen.height + “<br>” + “screen width: ” + screen.width + “<br>” + “screen colorDepth: ” + screen.colorDepth + “<br>” + “screen pixelDepth: ” + screen.pixelDepth + “<br>” + “screen availHeight: ” + screen.availHeight + “<br>” + “screen availWidth: ” + screen.availWidth; </script> </body> </html> Output Screen Information screen height: 864 screen width: 1536 screen colorDepth: 24 screen pixelDepth: 24 screen availHeight: 816 screen availWidth: 1536 Please note that we get the same information about the screen in the above two examples. Screen Object Properties List Below, we have covered all properties of the ”screen” object with a description. You need to use the ”screen” as a reference to access these properties. Property Description availHeight It gives the height of the screen without including the taskbar. availWidth It gives the width of the screen without including the taskbar. colorDepth It gives the depth of the color palette to display images. height It returns the total height of the screen. pixelDepth It is used to get the color resolution of the screen. width To get the total width of the screen. Print Page Previous Next Advertisements ”;

JavaScript – Browsers

JavaScript – Browsers Compatibility ”; Previous Next It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in. To get information about the browser your webpage is currently running in, use the built-in navigator object. Navigator Properties There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each. Sr.No. Property & Description 1 appCodeName This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer. 2 appVersion This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility. 3 language This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only. 4 mimTypes[] This property is an array that contains all MIME types supported by the client. Netscape only. 5 platform[] This property is a string that contains the platform for which the browser was compiled.”Win32″ for 32-bit Windows operating systems 6 plugins[] This property is an array containing all the plug-ins that have been installed on the client. Netscape only. 7 userAgent[] This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client. Navigator Methods There are several Navigator-specific methods. Here is a list of their names and descriptions. Sr.No. Description 1 javaEnabled() This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false. 2 plugings.refresh This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only. 3 preference(name,value) This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only. 4 taintEnabled() This method returns true if data tainting is enabled; false otherwise. Browser Detection There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user. <html> <head> <title>Browser Detection Example</title> </head> <body> <script type = “text/javascript”> var userAgent = navigator.userAgent; var opera = (userAgent.indexOf(”Opera”) != -1); var ie = (userAgent.indexOf(”MSIE”) != -1); var gecko = (userAgent.indexOf(”Gecko”) != -1); var netscape = (userAgent.indexOf(”Mozilla”) != -1); var version = navigator.appVersion; if (opera) { document.write(“Opera based browser”); // Keep your opera specific URL here. } else if (gecko) { document.write(“Mozilla based browser”); // Keep your gecko specific URL here. } else if (ie) { document.write(“IE based browser”); // Keep your IE specific URL here. } else if (netscape) { document.write(“Netscape based browser”); // Keep your Netscape specific URL here. } else { document.write(“Unknown browser”); } // You can include version to along with any above condition. document.write(“<br /> Browser version info : ” + version ); </script> </body> </html> Output On executing the above program, you will get the output similar to the following − Please note that you may get some more information about the browser depending upon the type of browser you are using. Print Page Previous Next Advertisements ”;

JavaScript – History API

JavaScript – History API ”; Previous Next Web History API In JavaScript, the history API allows us to access the browser’s history. It can be used to navigate through the history. JavaScript History API provides us with methods to manipulate window history object. History object is a property of JavaScript window object. The window history object contains the array of visited URLs in the current session The history API is very powerful tool to create may useful effects. For example, we can use it to implement history based undo redo system. How to use JavaScript History API? The History API is a very simple API to use. There are just a few methods and a property that you need to know about: back() − This method navigates back to the previous page in the history. forward() − This method navigates forward to the next page in the history. go() − This method navigates to a specific page in the history. The number that you pass to the go() method is the relative position of the page that you want to navigate to. For example, to navigate to the previous page in the history, you would pass -1 to the go() method. length − This property returns the length of the history list. It tells us the number of pages that have been visited by the user. Syntax Followings are the syntaxes to use the different methods and property of the history object − // Load the previous URL in the history list history.back(); // Load the next URL in the history list history.forward(); // Load the page through its number history.go(-2); // This will go to the previous 2nd page history.go(2); // This will go to the next 2nd page // Get the length of the history list const length = history.length; Loading Previous Page in History List The JavaScript history back() method of the history object loads the previous URL in the history list. We can also use the history go() method to load the previous page. The difference between these two methods is that back() method only load the immediate previous URL in history list but we can use the go() method to load any previous URL in the history list. Example: Using back() method to load previous page In the example below, we have used history back() method to load the previous page the user has already visited. Please note that if you have no previous page in the history list (i.e., you have not visited any page previously), the back() method will not work. We have implemented a back button, on clicking that we can load the previous visited page. <html> <body> <p> Click “Load Previous Page” button to load previous visited page </p> <button onclick=”goback()”> Load Previous Page </button> <p id = “output”> </p> <script> function goback() { history.back(); document.getElementById(“output”).innerHTML += “You will have gone to previous visited page if it exists”; } </script> </body> </html> Example: Using go() method to load the previous page In the example bellow, we have used the history go() method to load to the 2nd previous visited page from the current web page. <html> <body> <p> Click the below button to load 2nd previous visited page</p> <button onclick = “moveTo()”> Load 2nd Previous Page </button> <p id = “output”> </p> <script> function moveTo() { history.go(-2); document.getElementById(“output”).innerHTML = “You will have forwarded to 2nd previous visited page if it exists.”; } </script> </body> </html> Loading Next Page in History List The JavaScript history forward() method of the history object loads the next URL in the history list. We can also use the history go() method to load the next page. The difference between these two methods is that forward() method only loads the immediate next URL in history list but we can use the go() method to load any next URL in the history list. Example: Using forward() method to load next page In the below code, click the button to go to the next URL. It works as the forward button of the browser. <html> <body> <p> Click “Load Next Page” button to load next visited page</p> <button onclick = “goForward()”> Load Next Page </button> <p id = “output”> </p> <script> function goForward() { history.forward(); document.getElementById(“output”).innerHTML = “You will have forwarded to next visited page if it exists.” } </script> </body> </html> Example: Using go() method to load next page In the example below, we have used the go() method to move to the 2nd previous page from the current web page. <html> <body> <p> Click the below button to load next 2nd visited page</p> <button onclick = “moveTo()”> Load 2nd Next Page </button> <p id = “output”> </p> <script> function moveTo() { history.go(2); document.getElementById(“output”).innerHTML = “You will have forwarded to 2nd next visited page if it exists.”; } </script> </body> </html> Get the length of the history list We can use the history.length proerty to get the length of history list. Example Try the follwing example − <html> <body> <p> Click the below button to get the lenght of history list</p> <button onclick = “moveTo()”> Get Lenght of History List </button> <p id = “output”> </p> <script> const output = document.getElementById(“output”); function moveTo() { output.innerHTML = history.length; } </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – Fetch API

JavaScript – Fetch API ”; Previous Next What is a Fetch API? The JavaScript Fetch API is a web API that allows a web browser to make HTTP request to the web server. In JavaScript, the fetch API is introduced in the ES6 version. It is an alternative of the XMLHttpRequest (XHR) object, used to make a ”GET”, ”POST”, ”PUT”, or ”DELETE” request to the server. The window object of the browser contains the Fetch API by default. The Fetch API provides fetch() method that can be used to access resources asynchronously across the web. The fetch() method allows you to make a request to the server, and it returns the promise. After that, you need to resolve the promise to get the response received from the server. Syntax You can follow the syntax below to use the fetch() API in JavaScript – window.fetch(URL, [options]); OR fetch(URL, [options]); Parameters The fetch() method takes two parameters. URL − It is an API endpoint where you need to make a request. [options] − It is an optional parameter. It is an object containing the method, headers, etc., as a key. Return value It returns the promise, which you can solve using the ”then…catch” block or asynchronously. Handling Fetch() API Response with ”then…catch” Block The JavaScript fetch() API returns the promise, and you can handle it using the ”then…catch” block. Follow the syntax below to use the fetch() API with the ”then…catch” block. fetch(URL) .then(data => { // Handle data }) .catch(err=> { // Handle error }) In the above syntax, you can handle the ”data” in the ”then” block and the error in the ”catch” block. Example In the below code, we fetch the data from the given URL using the fetch() API. It returns the promise we handle using the ”then” block. First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page. <html> <body> <div id = “output”> </div> <script> const output = document.getElementById(”output”); const URL = ”https://jsonplaceholder.typicode.com/todos/5”; fetch(URL) .then(res => res.json()) .then(data => { output.innerHTML += “The data from the API is: ” + “<br>”; output.innerHTML += JSON.stringify(data); }); </script> </body> </html> Output The data from the API is: {“userId”:1,”id”:5,”title”:”laboriosam mollitia et enim quasi adipisci quia provident illum”,”completed”:false} Handling Fetch() API Response Asynchronously You can also solve the promise returned by the fetch() API asynchronously using the async/await keyword. Syntax Users can follow the syntax below to use the async/await keywords with the fetch() API. let data = await fetch(URL); data = await data.json(); In the above syntax, we used the ”await” keyword to stop the code execution until the promise gets fulfilled. After that, we again used the ”await” keyword with the data.json() to stop the execution of the function until it converts the data into the JSON format. Example In the code below, we have defined the getData()asynchronous function to fetch the to-do list data from the given URL using the fetch() API. After that, we convert the data into JSON and print the output on the web page. <html> <body> <div id = “output”> </div> <script> async function getData() { let output = document.getElementById(”output”); let URL = ”https://jsonplaceholder.typicode.com/todos/6”; let data = await fetch(URL); data = await data.json(); output.innerHTML += “The data from the API is: ” + “<br>”; output.innerHTML += JSON.stringify(data); } getData(); </script> </body> </html> Output The data from the API is: {“userId”:1,”id”:6,”title”:”qui ullam ratione quibusdam voluptatem quia omnis”,”completed”:false} Options with Fetch() API You can also pass the object as a second parameter containing the options as a key-value pair. Syntax Follow the syntax below to pass the options to the Fetch() API. fetch(URL, { method: “GET”, body: JSON.stringify(data), mode: “no-cors”, cache: “no-cache”, credentials: “same-origin”, headers: { “Content-Type”: “application/json”, }, redirect: “follow”, }) Options Here, we have given some options to pass to the fetch() API. method − It takes the ”GET”, ”POST”, ”PUT”, and ”DELETE” methods as a value based on what kind of request you want to make. body − It is used to pass the data into the string format. mode − It takes the ”cors”, ”no-cors”, ”same-origin”, etc. values for security reasons. cache − It takes the ”*default”, ”no-cache”, ”reload”, etc. values. credentials − It takes ”same-origin”, ”omit”, etc. values. headers − You can pass the headers with this attribute to the request. redirect − If you want users to redirect to the other web page after fulfilling the request, you can use the redirect attribute. Example: Making a GET Request In the below code, we have passed the “GET” method as an option to the fetch() API. Fetch () API fetches the data from the given API endpoint. <html> <body> <div id = “output”> </div> <script> let output = document.getElementById(“output”); let options = { method: ”GET”, } let URL = “https://dummy.restapiexample.com/api/v1/employee/2”; fetch(URL, options) .then(res => res.json()) .then(res => { output.innerHTML += “The status of the response is – ” + res.status + “<br>”; output.innerHTML += “The message returned from the API is – ” + res.message + “<br>”; output.innerHTML += “The data returned from the API is – ” + JSON.stringify(res.data); }) .catch(err => { output.innerHTML += “The error returned from the API is – ” + JSON.stringify(err); }) </script> </body> </html> Output The status of the response is – success The message returned from the API is – Successfully! Record has been fetched. The data returned from the API is – {“id”:2,”employee_name”:”Garrett Winters”,”employee_salary”:170750,”employee_age”:63,”profile_image”:””} Example (Making a POST Request) In the below code, we have created the employee object containing the emp_name and emp_age properties. Also, we have created the options object containing the method, headers, and body properties. We use the ”POST” as a value of the method and use the employee object after converting it into the string as a body value. We make a POST request to the API endpoint using the fetch() API to insert the data. After making the post request, you can see the response on

ECMAScript 2019

JavaScript – ECMAScript 2019 ”; Previous Next The ECMAScript 2019 standard was released in 2019. Important additions to this update include Array flat() and Array flatMap(), offering concise array manipulation methods. The Object.fromEntries() method simplifies object creation from key-value pairs. These improvements in ECMAScript 2019 aimed to enhance code conciseness and functionality. This chapter will discuss all the newly added features in ECMAScript 2019. New Features Added in ECMAScript 2019 Here are the new methods, features, etc., added to the ECMAScript 2019 version of JavaScript. Array.flat() Array.flatMap() Revised Array.Sort() Object.fromEntries() Optional catch binding Revised JSON.stringify() Revised Function.toString() Separator symbols allowed in string literals String.trimEnd() String.trimStart() JavaScript Array flat() Method The ECMAScript 2019 introduced Array.flat to the arrays. The JavaScript array flat() method is used to flatten the array by removing the nested array and adding its elements to the original array. Example In the code below, we used the array.flat() method to flatten the arr array. <html> <body> <div id = “output”>The flatten array is: </div> <script> const arr = [1, [10, 20], 30, [40, [50], 60], 70]; document.getElementById(“output”).innerHTML += arr.flat(); </script> </body> </html> Output The flatten array is: 1,10,20,30,40,50,60,70 JavaScript Array flatMap() The ECMAScript 2019 also introduced Array flatMap to arrays. The array flatMap() flatten the array after mapping the array elements with new elements. Example In the below code, we return the array of two elements from the callback function of the flatMap() method. After that, the flatMap() method flattens it. In the output, you can see that ”updated” is a single array. So, it first maps the current element to a new element or array and flattens it. <html> <body> <div id = “output”>The updated array is: </div> <script> const arr = [2, 4, 6, 8]; const updated = arr.flatMap((ele) => [ele * 2, ele * 3]); document.getElementById(“output”).innerHTML += updated; </script> </body> </html> Output The updated array is: 4,6,8,12,12,18,16,24 Revised Array sort() In ECMAScript 2019, JavaScript array.prototype.sort() method has been revised to make it stable. Before 2019, the behavior of the sort() method was not consistent in sorting the equal elements. It could not preserve the original order for the same array elements. Now, array.sort() method is stable as it uses the variation of the merge sort. Example In the below code, we have defined the watches array containing multiple objects. Each object of the array contains the brand and price property. We used the sort() method to sort the array based on the value of the brand property. In the output, you can see that it preserves the original order for the same brand name. <html> <body> <div id = “output”>The sorted array elements are: <br></div> <script> const watches = [{ brand: “Titan”, price: 1000 }, { brand: “Casio”, price: 1000 }, { brand: “Titan”, price: 2000 }, { brand: “Titan”, price: 3000 }] watches.sort((a, b) => a.brand.localeCompare(b.brand)) for (let obj of watches) { document.getElementById(“output”).innerHTML += JSON.stringify(obj) + “<br>”; } </script> </body> </html> Output The sorted array elements are: {“brand”:”Casio”,”price”:1000} {“brand”:”Titan”,”price”:1000} {“brand”:”Titan”,”price”:2000} {“brand”:”Titan”,”price”:3000} JavaScript Object fromEntries The Object fromEnteries() method allows you to create a new object from the 2-dimensional array. Each element of the array should be an array of length 2, containing the key-value pair for the object. Example In the below code, we have defined the 2D array containing the fruit name and price. After that, we used the Object.fromEntries() method to create an object from the array. <html> <body> <div id = “output”>The fruits object is : </div> <script> const entries = [[“Apple”, 20], [“Banana”, 40], [“watermelon”, 30]]; const fruits = Object.fromEntries(entries); document.getElementById(“output”).innerHTML += JSON.stringify(fruits); </script> </body> </html> Output The fruits object is : {“Apple”:20,”Banana”:40,”watermelon”:30} Optional catch binding After ECMAScript 2019, you can remove the ”catch” block parameter if you don”t need it. For example, before ECMAScript 2019, you must need the parameters with the catch block. try { } catch(error){ } After ECMAScript 2019, try { } catch { } Revised JSON.stringify() Before ECMAScript 2019, JavaScript JSON.stringify() method was not able to convert the Unicode characters into a string, but after ES10, it is possible, as shown in the example below. Example In the code below, we convert the Unicode character into the JSON string and then use the JSON.parse() method to parse the string. <html> <body> <div id = “output1”>The unicode string value is: </div> <div id = “output2”>The unicode JSON value is: </div> <script> let str = JSON.stringify(“u27A6”); document.getElementById(“output1”).innerHTML += str; document.getElementById(“output2”).innerHTML += JSON.parse(str); </script> </body> </html> Output The unicode string value is: “➦” The unicode JSON value is: ➦ Revised Function toString() Before ECMAScript 2019, when you used the toString() method with the function, it returned the function”s source code without comment, syntax, etc. After ES10, it returns the function with spaces, syntax, comments, etc. Example The toString() method returns the function after converting into the string in the below code. The resultant string contains the spaces, comments, etc. <html> <body> <div id = “output”>After converting the function to string is: </div> <script> function test() { return 10 * 20; } document.getElementById(“output”).innerHTML += test.toString(); </script> </body> </html> Output After converting the function to string is: function test() { return 10 * 20; } Separator symbols allowed in string literals After ECMAScript 2019, you can use the separator symbols u2028 and u2029)to separate the line and paragraph in the string. Example In the below code, we used the Unicode character to separate the line. However, you won”t be able to see separating lines directly as we use the innerHTML property to update the HTML. <html> <body> <div id = “output”>The string with seprator symbol is: </div> <script> let str = “Hiu2028”; document.getElementById(“output”).innerHTML += str; </script> </body> </html> JavaScript String trimEnd() The string trim() method was introduced in ECMAScript 2019. It is used to remove the whitespace from both ends of the string. The string.trimEnd() method removes the whitespaces from the end of the string. Example The code below removes the white spaces from the end of the string. <html> <body> <div id = “output”>After removing

JavaScript – Browser Object Model

JavaScript – Browser Object Model ”; Previous Next The Browser Object Model (BOM) in JavaScript refers to the objects provided by the browsers to interact with them. By using these objects, you can manipulate the browser”s functionality. For example, you can get the browser history and window size, navigate to different URLs, etc. The Browser object model is not standardized. It depends on which browser you are using. Here, we have listed all objects of the Browser Object Model with descriptions − Window − The ”window” object represents the current browser window. You can use it to manipulate the browser window. Document − The ”document” object represents the currently opened web page in the browser window. You can use it to customize the property of the document. Screen − It provides information about the user”s device”s screen. History − It provides the browser”s session history. Navigator − It is used to get the browser”s information like default language, etc. Location − The Location object is used to get the URL information, such as the hostname of the current web page. Console − The console object allows developers to access the browser”s console. JavaScript Window Object The JavaScript window object represents the browser”s window. We can use different methods and properties of the window object to manipulate current browser window. For example, showing an alert, opening a new window, closing the current window, etc. All the JavaScript global variables are properties of window object. All global functions are methods of the window object. The other objects listed above such as document, screen, history etc., are the properties of the window object. We can access these objects as properties of the window object. We can also access them with referencing the window object. Look at the below example snippet to access the document object – window.document.write(“Welcome to Tutorials Point”); or without window object − document.write(“Welcome to Tutorials Point”); The innerHeight and innerWidth properties of the window object are used to access the height and width of the browser window. We will learn JavaScript window object in detail in next chapters. JavaScript Document Object The document object is a property of the JavaScript window object. The whole HTML document is represented as a document object. The document object forms HTML DOM. It is root node of the HTML document. The document object can be accessed as window.document or just document. The document object provides us with many properties and methods to access the HTML elements and manipulate them. One such method is document.getElementById() to access the HTML element using its id. We can access an element with id as “text” using getElementById() method and manipulate it – Example <html> <body> <div id =”text”>This text will be changed. </div> <script> // Access the element with id as text const textDiv = document.getElementById(“text”); // Change the content of this element textDiv.innerHTML = “The text of this DIV is changed.”; </script> </body> </html> Output The text of this DIV is changed. JavaScript Screen Object In JavaScript, the screen object is a property of window object. It provides us with properties that can be used to get the information about the device window screen. We can access the screen object as window.screen or just screen. To get the width and height of the device screen in pixels we can use the screen.width and screen.height properties – Example <html> <body> <div id =”width”>Width of the device screen is </div> <div id =”height”>Height of the device screen is </div> <script> document.getElementById(“width”).innerHTML += screen.width + ” px.”; document.getElementById(“height”).innerHTML += screen.height + ” px.”; </script> <p> The above result may be different for different device.</p> </body> </html> Output Width of the device screen is 1536 px. Height of the device screen is 864 px. The above result may be different for different device. JavaScript History Object In JavaScript, the history object is also a property of the window object. It contains a list of the visited URLs in the current session. The history object provides an interface to manipulate the browser”s session history. The JavaScript history object can be accessed using window.history or just history. We can use the methods of history object to navigate the URLs in the history list. For example to go the previous page/URL in the history list, we can use history.back() method. JavaScript Navigator Object The JavaScript navigator object is also a property of the window object. Using the ”navigator” object, you can get the browser version and name and check whether the cookie is enabled in the browser. We can access the navigator object using window.navigator. We can also access it without using the window prefix. JavaScript Location Object The JavaScript ”location” object contains various properties and methods to get and manipulate the information of the browser”s location, i.e. URL. It”s also a property of JavaScript window object. We can use the properties and methods of the location object to manipulate the URL information. For example, to get the host from the current URL, we can use the window.location.host or just location.host. The host is property of the location object. Example <html> <body> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “The host of the current location is: ” + location.host; </script> </body> </html> Output The host of the current location is: www.tutorialspoint.com JavaScript Console Object The JavaScript console object allows us to access the debugging console of the browser. It is a property of the JavaScript window object. It can be accessed using window.console or just console. The console object provides us with different methods such as console.log(). The console.log() method is used to display the message in debugging console. What”s Next? We have provided detailed information about each of the above objects in separate chapters. Print Page Previous Next Advertisements ”;

JavaScript – Cookies

JavaScript and Cookies ”; Previous Next What are Cookies ? In JavaScript, cookies are piece of data stored in the user”s web browser. The cookies are stored in the key-value pair inside the browser. We can manipulate the cookies using cookie property of document object. We can set or store a cookie in key-value pair using the cookie property. We can read cookies using document”s cookie property and extract the desired information using destructuring. Why are Cookies needed? Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, you have logged in to a particular website on a particular web page. How do other webpages of the same website know your state that you have already completed the logged-in process? In this case, cookies are used. In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. Sometimes, cookies are also used for caching, increasing the website or application performance. How It Works ? Your server sends some data to the visitor”s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor”s hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier. Cookies are a plain text data record of 5 variable-length fields − Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. Domain − The domain name of your site. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. Secure − If this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. Name=Value − Cookies are set and retrieved in the form of key-value pairs Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client. Setting/ Storing Cookies JavaScript can manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this. document.cookie = “key1 = value1;key2 = value2;expires = date”; Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies” value will not be accessible. The cookie string contains the key-value pairs separated by the semi-colons. Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value. Example Try the following. It sets a customer name in an input cookie. <html> <head> <script type = “text/javascript”> function WriteCookie() { if( document.myform.customer.value == “” ) { alert(“Enter some value!”); return; } cookievalue = escape(document.myform.customer.value) + “;”; document.cookie = “name=” + cookievalue; document.write (“Setting Cookies : ” + “name=” + cookievalue ); } </script> </head> <body> <form name = “myform” action = “”> Enter name: <input type = “text” name = “customer”/> <input type = “button” value = “Set Cookie” onclick = “WriteCookie();”/> </form> </body> </html> Output Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma. Reading Cookies Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value. You can use strings” split() function to break a string into key and values as follows − Example Try the following example to get all the cookies. <html> <head> <script type = “text/javascript”> function ReadCookie() { var allcookies = document.cookie; document.write (“All Cookies : ” + allcookies ); // Get all the cookies pairs in an array cookiearray = allcookies.split(”;”); // Now take key value pair out of this array for(var i=0; i<cookiearray.length; i++) { name = cookiearray[i].split(”=”)[0]; value = cookiearray[i].split(”=”)[1]; document.write (“Key is : ” + name + ” and Value is : ” + value); } } </script> </head> <body> <form name = “myform” action = “”> <p> click the following button and see the result:</p> <input type = “button” value = “Get Cookie” onclick = “ReadCookie()”/> </form> </body> </html> Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it. Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine. Setting Cookies Expiry Date You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time. Example Try the following example. It illustrates how to extend the

JavaScript – addEventListener()

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 ”;

JavaScript – Storage API

JavaScript – Storage API ”; Previous Next What is Web Storage API? The web storage API in JavaScript allows us to store the data in the user”s local system or hard disk. Before the storage API was introduced in JavaScript, cookies were used to store the data in the user”s browser. The main problem with the cookies is that whenever browsers request the data, the server must send it and store it in the browser. Sometimes, it can also happen that attackers can attack and steal the data. In the case of the storage API, we can store the user”s data in the browsers, which remains limited to the user”s device. JavaScript contains two different objects to store the data in the local. localStorage sessionStorage Here, we have explained the local and session storage. The Window localStorage Object The localStorage object allows you to store the data locally in the key-value pair format in the user”s browser. You can store a maximum of 5 MB data in the local storage. Whatever data you store into the local storage, it never expires. However, you can use the removeItem() method to remove the particular or clear() to remove all items from the local storage. Syntax We can follow the syntax below to set and get items from the browser”s local storage. localStorage.setItem(key, value); // To set key-value pair localStorage.getItem(key); // To get data using a key In the above syntax, the setItem() method sets the item in the local storage, and the getItem() method is used to get the item from the local storage using its key. Parameters key − It can be any string. value − It is a value in the string format. Example In the below code, we set the ”fruit” as a key and ”Apple” as a value in the local storage inside the setItem() function. We invoke the setItem() function when users click the button. In the getItem() function, we get the value of the ”fruit” key from the local storage. Users can click the set item button first and then get the item to get the key-value pair from the local storage. <html> <body> <button onclick = “setItem()”> Set Item </button> <button onclick = “getItem()”> Get Item </button> <p id = “demo”> </p> <script> const output = document.getElementById(”demo”); function setItem() { localStorage.setItem(“fruit”, “Apple”); } function getItem() { const fruitName = localStorage.getItem(“fruit”); output.innerHTML = “The name of the fruit is: ” + fruitName; } </script> </body> </html> The localStorage doesn”t allow you to store the objects, functions, etc. So, you can use the JSON.stringify() method to convert the object into a string and store it in the local storage. Example: Storing the object in the local storage In the below code, we have created the animal object. After that, we used the JSON.stringify() method to convert it into the string and store it as a value of the ”animal” object. Users can click the set item button to set the object into the local storage and get the item button to get the key-value pair from the local storage. <html> <body> <button onclick = “setItem()”> Set Item </button> <button onclick = “getItem()”> Get Item </button> <p id = “demo”> </p> <script> const output = document.getElementById(”demo”); function setItem() { const animal = { name: “Lion”, color: “Yellow”, food: “Non-vegetarian”, } localStorage.setItem(“animal”, JSON.stringify(animal)); } function getItem() { const animal = localStorage.getItem(“animal”); output.innerHTML = “The animal object is: ” + animal; } </script> </body> </html> Example: Removing the items from the local storage In the below code, we set the ”name” and ”john” key-value pair in the local storage when the web page loads into the browser. After that, users can click the get item button to get the item from local storage. It will show you the name. You can click the get item button again after clicking the remove item button, and it will show you null as the item got deleted from the local storage. <html> <body> <button onclick = “getItem()”> Get Item </button> <button onclick = “removeItem()”> Remvoe Item </button> <p id = “demo”></p> <script> const output = document.getElementById(”demo”); localStorage.setItem(”name”, ”John”); function getItem() { output.innerHTML = “The name of the person is: ” + localStorage.getItem(”name”); } function removeItem() { localStorage.removeItem(”name”); output.innerHTML = ”Name removed from local storage. Now, you can”t get it.”; } </script> </body> </html> The Window sessionStorage Object The sessionStorage object also allows storing the data in the browser in the key-value pair format. It also allows you to store the data up to 5 MB. The data stored in the session storage expires when you close the tab of the browsers. This is the main difference between the session storage and local storage. You can also use the removeItem() or clear() method to remove the items from the session storage without closing the browser”s tab. Note – Some browsers like Chrome and Firefox maintain the session storage data if you re-open the browser”s tab after closing it. If you close the browser window, it will definitely delete the session storage data. Syntax Follow the syntax below to use the session storage object to set and get data from the session storage. sessionStorage.setItem(key, value); // To set key-value pair sessionStorage.getItem(key); // To get data using a key The setItem() and getItem() methods give the same result with the sessionStorage object as the localStorage object. Parameters key − It is a key in the string format. value − It is a value for the key in the string format. Example In the below code, we used the ”username” as a key and ”tutorialspoint” as a value. We store the key-value pair in the sessionStorage object using the setItem() method. You can click the get item button after clicking the set item button to get the key-value pair from the session storage. <html> <body> <button onclick = “setItem()”> Set Item </button> <button onclick = “getItem()”> Get Item </button> <p id = “output”> </p> <script> const output = document.getElementById(”output”); function setItem() { sessionStorage.setItem(“username”,

JavaScript – ES6

JavaScript – ES5 ”; Previous Next The ES6 version of JavaScript was released in 2015, marking the second major revision of JavaScript. The ES6 is also known as ECMAScript 2015. Some of the important features introduced in ES6 are arrow functions, let and const keywords, Classes, res parameters, etc. This chapter will discuss all the newly added features in ES6 version. New Added Features in ES6 Here are the new methods, features, etc., added to the ES6 version of JavaScript. Arrow Functions Array find() Array findIndex() Array from() Array keys() Classes const keyword Default Parameters For/of Function Rest Parameter JavaScript Modules let keyword Map Objects New Global Methods New Math Methods New Number Methods New Number Properties Promises Set Objects String.endsWith() String.includes() String.startsWith() Symbol The spread Operator Here, we have explained each feature in detail with examples. JavaScript Arrow Functions The arrow function is a way to write the shorter function code. The concept of the arrow functions allows you to define the function without using the function keyword, curly braces, and return keyword. Example In the below code, func() is a regular function, and the variable subtracts stores the arrow function. <html> <body> <div id = “output”>The subtraction of 20 and 10 is: </div> <script> /* Normal function function func(a, b) { return a – b; } */ // Arrow function const subtract = (a, b) => a – b; document.getElementById(“output”).innerHTML += subtract(20, 10); </script> </body> </html> Output The subtraction of 20 and 10 is: 10 JavaScript Array find() Method The JavaScript array.find() method returns the first element that follows the particular condition. Example In the below code, we find the first array element whose length is less than 4 using the array.find() method. <html> <body> <div id = “output”>The first array element whose length is less than 4 is: </div> <script> const strs = [“Hello”, “World”, “How”, “are”, “You”]; function func_len(value, index, array) { return value.length < 4; } document.getElementById(“output”).innerHTML += strs.find(func_len); </script> </body> </html> Output The first array element whose length is less than 4 is: How JavaScript Array findIndex() The JavaScript array.findIndex() method is similar to the array.find() method, but it returns the index of the first element that matches the particular condition. It returns the 0-based index. Example In the below code, we find the index of the first element whose length is less than 4 using the array.findIndex() method. <html> <body> <div id = “output”>The first array element whose length is less than 4 is: </div> <script> const strs = [“Hello”, “World”, “How”, “are”, “You”]; function func_len(value, index, array) { return value.length < 4; } document.getElementById(“output”).innerHTML += strs.findIndex(func_len); </script> </body> </html> Output The first array element whose length is less than 4 is: 2 JavaScriipt Array from() The JavaScript Array.from() method creates an array from the iterable passed as an argument. Example In the below code, we create an array from the string using the Array.from() method. However, you can also pass iterable as an argument of the Array.from() method. <html> <body> <div id = “output”>The array from the Hello string is: </div> <script> document.getElementById(“output”).innerHTML += Array.from(“Hello”); </script> </body> </html> Output The array from the Hello string is: H,e,l,l,o JavaScript Array keys() The JavaScript array.keys() method returns an iterator to iterate the keys. The keys of the array element are indexes of the array elements. Example In the below code, we use the keys() method to get the iterators of keys of the nums[] array. After that, we use the for/of loop to traverse the keys of the array. <html> <body> <div id = “demo”>The keys of the nums array is: <br></div> <script> const output = document.getElementById(“demo”); const nums = [45, 67, 89, 342, 123, 12]; const iteratorNums = nums.keys(); for (let key of iteratorNums) { output.innerHTML += key + “<br>”; } </script> </body> </html> Output The keys of the nums array is: 0 1 2 3 4 5 JavaScript Classes Classes are essential in the object-oriented programming language. It is a blueprint for the object. You can use the class keyword to define the class. You can add constructors, properties, and methods to the class body. To access class properties and methods, you can use the class instance. Example In the below code, we have defined the animal class. The constructor initializes the value of the name and isVegetarian property. The getInfo() method returns the animal information. We created the object of the animal class and used it to invoke the getInfo() method of the class. <html> <body> <div id = “output”>The animal information is: </div> <script> class animal { constructor(name, isVegetarian) { this.name = name; this.isVegetarian = isVegetarian; } getInfo() { return “Name : ” + this.name + “, ” + “isVegetarian? : ” + this.isVegetarian; } } const lion = new animal(“Lion”, false); document.getElementById(“output”).innerHTML += lion.getInfo(); </script> </body> </html> Output The animal information is: Name : Lion, isVegetarian? : false JavaScript const keyword The JavaScript const keyword is used to declare the constant variables. You need to initialize the constant variables while declaring them. Example In the below code, the ”fruit” is a constant variable. You can”t reinitialize its value. <html> <body> <div id = “output”>The value of the fruit variable is: </div> <script> const fruit = “Apple”; // fruit = “Banana”; This is Invalid document.getElementById(“output”).innerHTML += fruit; </script> </body> </html> Output The value of the fruit variable is: Apple JavaScript let keyword The JavaScript let keyword is used to define the blocked scope variables. Example In the below code, we have defined the variable ”a” using the let keyword inside the ”if” block. It can”t be accessible outside the ”if” block due to its scoping behavior. <html> <body> <div id = “output”> </div> <script> if (true) { let a = 20; document.getElementById(“output”).innerHTML += “The value of a is: ” + a; } // You can”t access it here. </script> </body> </html> Output The value of a is: 20 JavaScript Default Parameters The default parameters mean function parameters can have default values. When you don”t pass enough