JavaScript – Dynamic Imports ”; Previous Next Dynamic Imports Whenever the application code grows and contains thousands of lines, it is important to split the code into modules. Modules allow developers to break down complex codes and use them in different files by importing. In JavaScript modules chapter, you learned to import and export objects from the modules, but it was a static import, as we load them at the top of the code. Sometimes, we need to import the modules whenever needed rather than importing them statically to improve the performance of the web application. It is also called dynamic imports. The import() Expression for Dynamic Imports Whenever you need to import a module dynamically, you can use the import() expression, which returns the promise. We can import the module dynamically using the import() expression anywhere in the code. Syntax Users can follow the syntax below to import modules dynamically using the import() expression. import(moduleName).then(module => { // Use the module here. }); In the above syntax, we use the then() method with the import() expression to resolve the promise. Parameters moduleName − It takes a module name or path as a parameter, which we need to load dynamically. Return Value It returns the promise. Examples of Dynamic Import Example 1 Filename: test.js In the code below, we export the ”val1” variable containing the integer value. export const val1 = 11; Filename: test.html In the code below, we have used the if-else statement. We import the module and use its objects in the if() block. This way, we can import modules dynamically using the import() expression. <html> <body> <div>Example 1 – dynamic import in JavaScript</div> <div id = “output”> </div> <script type=”module”> let output = document.getElementById(”output”); let val = 2; if (val < 5) { // Importing the module import(”./test.js”).then(module => { output.innerHTML = “The imported value is ” + module.val1; }); } else { output.innerHTML = “Value is greater than 5″; } </script> </body> </html> Output Example 1 – dynamic import in JavaScript The imported value is 11 Example 2 Filename: test.js In the code below, we have defined the add() function, which returns the sum of two numbers. export function add(a, b) { return a + b; } Filename: test.html In the code below, we have added the ”click” event listener to the button. When a user clicks the button, it loads the ”test.js” module. Here, we used the async/await to handle the promise returned by the import() expression. After that, we use the add() function of the module to sum two numbers, and users can observe the summation result in the output. <html> <body> <div>Example 2 – dynamic imports in JavaScript</h2> <div id = “output”> </div> <button id = “button”> Click me </button> <script type=”module”> let output = document.getElementById(”output”); let btn = document.getElementById(”button”); //When the button is clicked, load the module btn.addEventListener(”click”, async () => { let module = await import(”./test.js”); let result = module.add(2, 3); output.innerHTML = “The sum of 2 and 3 is ” + result; }); </script> </body> </html> Output Example 2 – dynamic imports in JavaScript The sum of 2 and 3 is 5 This way, developers can import modules dynamically in the function, if-else block, etc., whenever needed rather than importing them at the top of the code. Print Page Previous Next Advertisements ”;
Category: javascript
JavaScript – Blob
JavaScript – Blob ”; Previous Next What is blob in JavaScript? In JavaScript, a Blob is an object that is a group of bytes representing the data stored in the file. We can easily easily read the content of the Blob object as an ArrayBuffer, so it is very useful to store the binary data. The Blob object is used to handle the raw binary data, which we can create from the plain text, file data, etc. Syntax Users can follow the syntax below to use the Blob() constructor to create a blob object. new Blob(BlobContent, Options); OR new Blob(BlobContent, {type: Type of the Blob content}); In the above syntax, Blob() constructor takes two parameters and returns an instance of the Blob object. Developers can set the values of the ”type” option based on the `BlobContent`. Parameters The Blob() constructor takes two parameters, as given below. BlobContent − It is a text, data, or file content. Options − It is an optional object containing various options for BlobContent. The ”type” is an important property in the Options object. It contains the MIME-type of the BlobContent as a value. For example, to store plain text in the blob object, you can use ”text/plain” as a MIME type; for images, you can use ”image/jpg” or ”image/png”, etc. Example In the below example code, we have used the blob() constructor to create a blob object. We have passed the ”Hello World!” string as a first parameter and the ”text/plain” MIME type for the content as a second parameter of the blob() constructor. After that, we have created the instance of the FileReader() object and used the readAsText() method to read the content of the blob object. In the output, we can see that it prints the plain text, which is the content of the blob object. <html> <body> <h2> JavaScript – Blob Object </h2> <h3 id = “output”> </h3> <script> var data = “Hello World”; var blob = new Blob([data], { type: ”text/plain” }); // Using the fileReader object to read the blob var reader = new FileReader(); reader.addEventListener(“loadend”, function (e) { var text = reader.result; document.getElementById(“output”).innerHTML = text; }); // Start reading the blob as text reader.readAsText(blob); </script> </body> </html> Blob URLs In the above section, we have learned to use the blob object. Furthermore, we can also create the URL using the blob object. As any particular URL refers to the file in the local file system, the blob URL referes to the content of the blob object. Also, we can use the blob URL as an actual URL with the <a> or <img> tag. Let”s take a look at the example below to create a URL from the blob object. Example: Rendering text content using the Blob URL In the example below, we have created the instance of the blob object and passed text content as a parameter. After that, we used the createObjectURL() method to create a blob URL. Next, we have updated the value of the ”href” attribute of the ”<a>” with the blob URL. In the output, when you click the URL, it shows you the content stored in the blob object. <html> <body> <h2> JavaScript – Blob URL </h2> <a href = “#” id = “download”> Download Text File </a> <script> // Creating file using Blob object var data = “This file contains the content of the blob object.”; var blob = new Blob([data], { type: ”text/plain” }); // Creating URL from Blob object var url = URL.createObjectURL(blob); var a = document.getElementById(“download”); // Updating the `href` attribute”s value a.href = url; </script> </body> </html> Example: Rendering an Image Using the Blob URL In this example, we have used the file input to get the image as input. Whenever the user uploads the image, we create the blob object using the file content. After that, we create a URL from the blob object and use it as a value of the ”src” attribute of the ”” tag to render the image on the web page. <html> <body> <h2> JavaScript – Blob URL </h2> <h3> Upload image file </h3> <input type = “file” id = “fileInput” /> <div id = “output”> </div> <script> // Read the file and create a blob document.getElementById(”fileInput”).addEventListener(”change”, function () { var file = this.files[0]; var reader = new FileReader(); reader.onload = function () { // Create a blob var blob = new Blob([new Uint8Array(this.result)], { type: file.type }); // Create an object URL var url = URL.createObjectURL(blob); // Set the object URL as the source of an image document.getElementById(”output”).innerHTML = ”<img src=”” + url + ”” />”; }; reader.readAsArrayBuffer(file); }); </script> </body> </html> Blob Advantages & Disadvantages Here are some advantages and disadvantages of using the blob objects. Advantages Blob objects are ideal for handling large binary data files on the web. Developers can fetch the data in chunks by using the blob objects, which improves the performance of the application. Blob objects can be used with the File API to perform the file operations in the browser. Disadvantages Large blob objects can consume significant memory and resources, which can impact the overall application performance and use experience. Handling the binary data using the blob object can introduce security concerns to the code. Older browsers do not support blob. Print Page Previous Next Advertisements ”;
JavaScript – User Defined Iterators ”; Previous Next In JavaScript, an iterable is an object which has Symbol.iterator() method in the object prototype. Some examples of iterable are array, set, map, string, etc. The Symbol.iterator() method returns an object containing the next() method is called iterator. Here, the next() method returns the elements of iterable in each call. The next() Method The next() method of the iterator object returns an object containing two key-value pairs given below. value − The value key contains the element as a value. done − The done key contains the boolean value. It contains true if all iterations of iterable are finished. Otherwise, it contains false. Example In the example below, we have created the array and stored the array iterator in the ”iter” variable. After that, we use the next() method of the iterator object to get the next value. The output shows that the next() method returns the object containing ”value” and ”done” properties. The last iteration returns the object containing the ”done” property only. <html> <head> <title> JavaScript – Iterators </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); const nums = [10, 72, 45]; const iter = nums[Symbol.iterator](); output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; </script> </body> </html> Output {“value”:10,”done”:false} {“value”:72,”done”:false} {“value”:45,”done”:false} {“done”:true} User-defined Iterators In the above part, we have looked at how an iterator works in JavaScript. The Symbol.iterator() method returns the object containing the next() method, and whenever we execute the next() method, it returns an object. So, in the same way, we can implement the user-defined iterators. Example In the example below, we have created the custom iterator using the function. The function returns the object containing the next() method. The next() method returns the object containing the array element and the false boolean value from the nth index if n is less than the array length. If the n is greater than or equal to the array”s length, it returns the object containing only the ”done” property with a ”true” boolean value. After that, we use the iter.next() syntax to get the next array element. <html> <head> <title> JavaScript – User defined iterators </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); function customIterator(chars) { // To track index let n = 0; return { // next() method next() { if (n < chars.length) { return { value: chars[n++], done: false } } return { done: true } } } } const chars = [”A”, ”C”, ”E”]; const iter = customIterator(chars); output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; output.innerHTML += JSON.stringify(iter.next()) + “<br>”; </script> </body> </html> Output {“value”:”A”,”done”:false} {“value”:”C”,”done”:false} {“value”:”E”,”done”:false} {“done”:true} {“done”:true} The above code uses the function to define the iterator. So, you can”t use the for…of loop with the iterator. Let”s learn to define the iterator using the object in the example below. Example In the example below, we add a function as a value of the ”Symbol.iterator” key. The function returns the next() method. The next() method returns the odd numbers. If the value of the odd number is 9, it finishes the iteration by returning the {done: true} object. Here, we created the iterator using the object. So, you can use the for…of loop. The loop will automatically execute the next() method of the iterator and returns a value of the ”value” property of the object returned by the next() method. <html> <head> <title> JavaScript – User defined iterators </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); // Empty object oddNum = {}; // Add iterator oddNum[Symbol.iterator] = function () { let p = -1; done = false; return { next() { p += 2; if (p == 9) return { done: true } return { value: p, done: done }; } }; } for (const odd of oddNum) { output.innerHTML += odd + “<br>”; } </script> </body> </html> Output 1 3 5 7 You should create user-defined iterators when they need customization in the traversal of iterable. For example, to traverse alternative array elements, to get even or odd numbers from an iterator, etc. Print Page Previous Next Advertisements ”;
JavaScript – Image Map
JavaScript – Image Map ”; Previous Next You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags. The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign. The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use. The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot. Example The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image. <html> <head> <title>Using JavaScript Image Map</title> <script type = “text/javascript”> function showTutorial(name) { document.myform.stage.value = name } </script> </head> <body> <form name = “myform”> <input type = “text” name = “stage” size = “20” /> </form> <!– Create Mappings –> <img src = “/images/usemap.gif” alt = “HTML Map” border = “0” usemap = “#tutorials”/> <map name = “tutorials”> <area shape=”poly” coords = “74,0,113,29,98,72,52,72,38,27” href = “/perl/index.htm” alt = “Perl Tutorial” target = “_self” onMouseOver = “showTutorial(”perl”)” onMouseOut = “showTutorial(””)”/> <area shape = “rect” coords = “22,83,126,125” href = “/html/index.htm” alt = “HTML Tutorial” target = “_self” onMouseOver = “showTutorial(”html”)” onMouseOut = “showTutorial(””)”/> <area shape = “circle” coords = “73,168,32” href = “/php/index.htm” alt = “PHP Tutorial” target = “_self” onMouseOver = “showTutorial(”php”)” onMouseOut = “showTutorial(””)”/> </map> </body> </html> Output You can feel the map concept by placing the mouse cursor on the image object. Print Page Previous Next Advertisements ”;
JavaScript – Validations
JavaScript – Form Validation ”; Previous Next Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server. JavaScript provides a way to validate form”s data on the client”s computer before sending it to the web server. Form validation generally performs two functions. Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data. Example We will take an example to understand the process of validation. Here is a simple form in html format. <html> <head> <title>Form Validation</title> <script type = “text/javascript”> // Form validation code will come here. </script> </head> <body> <form action = “/cgi-bin/test.cgi” name = “myForm” onsubmit = “return(validate());”> <table cellspacing = “2” cellpadding = “2” border = “1”> <tr> <td align = “right”>Name</td> <td><input type = “text” name = “Name” /></td> </tr> <tr> <td align = “right”>EMail</td> <td><input type = “text” name = “EMail” /></td> </tr> <tr> <td align = “right”>Zip Code</td> <td><input type = “text” name = “Zip” /></td> </tr> <tr> <td align = “right”>Country</td> <td> <select name = “Country”> <option value = “-1” selected>[choose yours]</option> <option value = “1”>USA</option> <option value = “2”>UK</option> <option value = “3”>INDIA</option> </select> </td> </tr> <tr> <td align = “right”></td> <td><input type = “submit” value = “Submit” /></td> </tr> </table> </form> </body> </html> Basic Form Validation First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function. <script type = “text/javascript”> // Form validation code will come here. function validate() { if( document.myForm.Name.value == “” ) { alert( “Please provide your name!” ); document.myForm.Name.focus() ; return false; } if( document.myForm.EMail.value == “” ) { alert( “Please provide your Email!” ); document.myForm.EMail.focus() ; return false; } if( document.myForm.Zip.value == “” || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( “Please provide a zip in the format #####.” ); document.myForm.Zip.focus() ; return false; } if( document.myForm.Country.value == “-1” ) { alert( “Please provide your country!” ); return false; } return( true ); } </script> Data Format Validation Now we will see how we can validate our entered form data before submitting it to the web server. The following example shows how to validate an entered email address. An email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign. Example Try the following code for email validation. <script type = “text/javascript”> function validateEmail() { var emailID = document.myForm.EMail.value; atpos = emailID.indexOf(“@”); dotpos = emailID.lastIndexOf(“.”); if (atpos < 1 || ( dotpos – atpos < 2 )) { alert(“Please enter correct email ID”) document.myForm.EMail.focus() ; return false; } return( true ); } </script> Print Page Previous Next Advertisements ”;
JavaScript – Currying
JavaScript – Currying ”; Previous Next In JavaScript, currying is a functional programming technique that is used to transform a function that takes multiple arguments into a sequence of functions that each takes a single argument. Currying is mainly used in event handling and to avoid passing the same variable as a function argument multiple times. How to achieve currying in JavaScript? There are two different ways to achieve currying in JavaScript, as given below. Using the closures function Using the bind() method Currying using closures In JavaScript, closures is a technique in which inner functions can access the variables of the outer functions. To achieve currying using the closures technique, we can use the sequence of functions, each taking a single argument. Syntax Users can follow the syntax below to achieve currying using the closures. function funcName(a) { return function (b) { // add more functions // OR return a * b; } } funcName(a)(b); In the above syntax, ”funcName()” function takes a single parameter, and it contains the inner function. The inner function also takes 1 parameter, and we use parameters of the outer and inner functions in the body of the inner function. The above function given in the syntax is similar to the below function. function funcName(a, b) { return a * b; } funcName(a, b); Let”s understand currying via examples. Example In the code below, we have created the mul() function, which takes the single value as a parameter and returns the function taking ”b” as a parameter. The inner function also returns another function, which takes the ”c” as a parameter and returns the multiplication of the ”a’, ”b’, and ”c’. When we call mul(2) function, it returns the whole inner function as shown below. return function (b) { return function (c) { return a * b * c; } } When we call the mul(2)(3) function, return function (c) { return a * b * c; } When we call mul(2)(3)(4), it returns the result from the second inner function. In the output, you can observe that the function returns the result 24, which is the multiplication of 3 values. <html> <head> <title>JavaScript currying using using closures</title> </head> <body> <div id = “output”> </div> <script> // Achieving the currying function mul(a) { return function (b) { return function (c) { return a * b * c; } } } // Calling the currying function let result = mul(2)(3)(4); document.getElementById(“output”).innerHTML = “The result is: ” + result; </script> </body> </html> Output The result is: 24 This way, currying helps to make code more modular and reusable as it uses higher-order functions. Whenever it is a must to pass a number of arguments equal to the parameters of the function to get accurate results, currying is useful. For example, if you don”t pass 3 arguments in the above example, it won”t return the result. Currying using bind() method In JavaScript, the bind() method is used to create a new function and store it in the variable. The bind() is often used to partially prepend arguments to the current arguments of the function, effectively allowing you to curry functions. Syntax Users can follow the syntax below to use the bind() method to achieve currying in JavaScript. let multiplyByTwo = multiply.bind(null, 2); let multiplyByTwoAndThree = multiplyByTwo.bind(null, 3); multiplyByTwoAndThree(4); // Outputs: 24 In the above syntax, ”multiply” can be a function taking multiple arguments. We prepend arguments one by one using the bind() method and achieve currying. Example In the code below, the multiply() function takes 3 arguments and returns the multiplication result. The ”multiply.bind()”, adds one argument to the multiply() function, and returns the updated function. Similarly, the ”multiplyByTwoAndThree()” function stores the multiply function having two predefined arguments bound to it. When we call the ”multiplyByTwoAndThree()” function with the single argument, it returns the 60, multiplication of all 3 arguments. <html> <head> <title>JavaScript currying using bind() method</title> </head> <body> <div id = “output”> </div> <script> // Original multiply function that accepts three arguments function multiply(x, y, z) { return x * y * z; } // Using the bind() method to achieve currying by partially applying the first argument (2) let multiplyByTwo = multiply.bind(null, 2); // Further currying by partially applying the second argument (3). let multiplyByTwoAndThree = multiplyByTwo.bind(null, 3); // Finally calling the curried function with the third argument (10) and outputting the result document.getElementById(“output”).innerHTML = “The result is: ” + multiplyByTwoAndThree(10); </script> </body> </html> Output The result is: 60 Use cases of Currying The currying technique is used in a lot of scenarios in real-time software development as it allows code to be more modularized and reusable. Here, we have given some real-time use cases of currying. Currying can be used to handle asynchronous operations, in which functions return the promises. It is even helpful in handling situations where we need to partially apply functions with specific arguments that can represent the current context of the event. It allows the creation of highly configurable middleware functions that can be used across different parts of the code. Print Page Previous Next Advertisements ”;
JavaScript – DOM Animation
JavaScript – DOM Animation ”; Previous Next The DOM animation can be achieved by changing the DOM element”s style using JavaScript. When changes are gradual and time interval is small, the animation looks continuous. Generally, there are three ways to animate a DOM element: Using CSS transitions − It utilizes pre-defined animation styles in CSS triggered by changes in the element”s properties. Using CSS animations − It offers more control over animation timing and behavior by defining keyframes and animation properties within the CSS file. Using JavaScript − It provides the most flexibility, allowing you to dynamically manipulate style properties and create complex animations directly within your JavaScript code. This chapter provides a basic understanding of how to animate DOM elements using JavaScript. Animate DOM Elements with JavaScript JavaScript can be used to change the style of the DOM element. You change the style of the DOM element after a particular time frame to animate them. For example, you can use the setInterval() method to change the position of the DOM element to move it from one position to another with animation. Similarly, you can update CSS properties like ‘animation’, etc., to animate the element dynamically. Furthermore, the requestAnimationFrame() method can also be used to animate the DOM elements. Below, you will learn different ways to animate the DOM elements. Animate DOM elements using setInterval() method You can invoke a setInterval() method after each time frame and change the style of the DOM element to animate them. However, you can keep the time frame small to run animation smoothly. Syntax Follow the syntax below to use the setInterval() method to animate DOM elements. let id = setInterval(frame_func, timeframe); function frame_func() { if (animation_end) { clearInterval(id); } else { // change style to animate } } In the above syntax, we start the animation using the setInterval() method and call the frame_func() after every ‘timeframe’ milliseconds. In the frame_func() function, we have defined the condition to end or continue the animation. Example In the below code, we have styled the <div> elements. When users click the button, it calls the startAnimation() function. In the startAnimation() function, we have defined the ‘pos’ variable and initialized it with 0, representing the initial position of the div element. After that, we used the setInterval() method to invoke the animationFrame() function after every 5 milliseconds. In the animationFrame() function, if the position of the inner div becomes 350, we stop the animation using the clearInterval() method. Otherwise, we change the left position of the inner div. When you click the button, it will move the inner div element from left to right. <!DOCTYPE html> <html> <head> <style> #parent { width: 700px; height: 50px; position: relative; background: yellow; } #child { width: 50px; height: 50px; position: absolute; background-color: red; } </style> </head> <body> <div id = “parent”> <div id = “child”> </div> </div> <br> <button onclick = “startAnimation()”> Animate Div </button> <script> function startAnimation() { const elem = document.getElementById(“child”); // Starting position let pos = 0; // Changing frames for animation let id = setInterval(animationFrame, 5); function animationFrame() { // Stop the animation if (pos == 350) { clearInterval(id); } else { pos++; elem.style.left = pos + “px”; } } } </script> </body> </html> Example In the below code, the background color of the <div> element is green. We use the setInterval() method to call the animationFrame() function after every 50 milliseconds. In the animationFrame() function, we change the opacity of the <div> element by 0.1. We stop the animation when the opacity becomes less than or equal to 0 using the clearInterval() method. <!DOCTYPE html> <html> <head> <style> #parent { width: 700px; height: 200px; background: green; } </style> </head> <body> <div id = “parent”> </div> <br> <button onclick = “startAnimation()”> Animate Div </button> <script> function startAnimation() { const parent = document.getElementById(“parent”); let opacity = 1; let id = setInterval(animationFrame, 50); function animationFrame() { if (opacity <= 0) { // Stop animation clearInterval(id); parent.style.opacity = 1; parent.style.backgroundColor = “red”; } else { // Decrease the opacity parent.style.opacity = opacity; opacity = opacity – 0.1; } } } </script> </body> </html> Animate DOM elements using requestAnimationFrame() method The requestAnimationFrame() method is used to animate the DOM elements like the setInterval() method. It executes the tasks continuously and repaints the next frame in the browser. The requestAnimationFrame() method makes rendering more efficient than the setInterval() method. Syntax Follow the syntax below to use the requestAnimationFrame() method to animate DOM elements. function animate() { // Animation logic // Request the next animation frame requestAnimationFrame(animate); } // Animation loop animate(); Let’s understand how the requestAnimationFrame() method works. You pass the callback function as an argument of the requestAnimationFrame() method to execute the next frame. The web browser will execute the callback before repainting the next frame. The callback function will update the DOM element. The browser will repaint the DOM element. Again, the browser will call the callback function, and the loop will continue. You can use the cancelAnimationFrame() method to cancel animation. Example In the code below, we have defined the startAnimation() and stopAnimation() functions and invoked them when the user clicks the button. In the startAnimation() function, we increment the value of the ‘pos’ by 1, and update the left position of the child div element. After that, we used the requestAnimationFrame() method to paint the next frame in the web browser. It will move the child div element from left to right in the parent div element. The stopAnimation() function uses the cancelAnimationFrame() method to stop the animation. It takes the id returned by the requestAnimationFrame() method as an argument. <!DOCTYPE html> <html> <head> <style> #parent {width: 700px; height: 50px; position: relative;background: yellow;} #child {width: 50px;height: 50px; position: absolute; background-color: red;} </style> </head> <body> <div id = “parent”> <div id = “child”> </div> </div> <br> <button onclick = “startAnimation()”> Animate Div </button> <button onclick = “stopAnimation()”> Stop Animation </button> <script> let animationId; let pos = 0; function startAnimation() { const elem = document.getElementById(“child”);
JavaScript – Page Printing
JavaScript – Page Printing ”; Previous Next Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object. The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example. Example Try the following example. <html> <head> <script type = “text/javascript”> <!– //–> </script> </head> <body> <form> <input type = “button” value = “Print” onclick = “window.print()” /> </form> </body> <html> Although it serves the purpose of getting a printout, it is not a recommended way. A printer friendly page is really just a page with text, no images, graphics, or advertising. You can make a page printer friendly in the following ways − Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example. If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!– PRINT STARTS HERE –>….. <!– PRINT ENDS HERE –> and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors. Example Create a button with an onclick event that is attached with the printpage() method, & it should be triggered when we want to print the page. When the user clicks the button then printpage() method (in the script tag) will be called, which may contains some code that helps to print the page. <html> <head> <title>Print Page</title> <script> function printpage() { window.print(); } </script> </head> <body> <h2>This is a sample page to print</h2> <button onclick=”printpage()”>Print Page</button> </body> </html> When the user clicks the button, the browser”s print dialog box will open, allowing them to print your HTML document as displayed on their current window. Here are some additional things to keep in mind when using JavaScript to print a page: The print() method will only print the content of the current window. If you want to print multiple pages, you will need to call the print() method for each page. The print() method will not print any content that is hidden from view. For example, if you have an element with the style property set to “display: none”, it will not be printed. The print() method will not print any content that is loaded dynamically after the page has loaded. For example, if you use JavaScript to load an image from a server, the image will not be printed. If you need to print more complex content, such as a table or a form, you may need to use a different method, such as generating a PDF file or using a third-party printing library. How to Print a Page? If you don’t find the above facilities on a web page, then you can use the browser”s standard toolbar to get print the web page. Follow the link as follows. File → Print → Click OK button. Print Page Previous Next Advertisements ”;
JavaScript – Reference Type
JavaScript – Reference Type ”; Previous Next JavaScript Reference Type There are two types of data types in JavaScript: primitive and reference type. Primitive data types are immutable, which means that they cannot be changed. The primitive data types in JavaScript are: Number, String, Boolean, Undefined, Null, Symbol. Reference data types are mutable, which means that they can be changed. The reference data types in JavaScript are: Object, Array, Function. When you assign a primitive data type to a variable, the variable gets a copy of the value. When you assign a reference data type to a variable, the variable gets a reference to the value. This means that if you change the value of a reference data type, the change will be reflected in all of the variables that reference that value. For example, the following code creates two variables, x and y, and assigns them the value 10: let x = 10; let y = 10; The variables x and y both have a copy of the value 10. If you change the value of x, the value of y will not change. x = 20; console.log(x); // 20 console.log(y); // 10 The following code creates two variables, x and y, and assigns them an array: const x = [1, 2, 3]; const y = x; The variables x and y both reference the same array. If you change the value of the array that x references, the change will be reflected in the array that y references. x[0] = 4; console.log(x); // [4, 2, 3] console.log(y); // [4, 2, 3] It is important to understand the difference between primitive and reference data types in JavaScript so that you can write code that is efficient and predictable. Objects and functions are the two main reference types in JavaScript and are explained as follows. Object Objects are unordered collections of key-value pairs, where keys are strings or symbols, and values can be any data type, including other objects. const person = { firstName: “John”, lastName: “Doe”, age: 30 }; Function Functions are also reference types in JavaScript. Functions are special types of objects that can be invoked (called) to perform a task. function greet(name) { alert(“Hello, ” + name + “!”); } Examples Example 1: Object Mutability In this example, we demonstrate object mutability for which first an object is created and then modifications are made through that reference which in turn affect the original object. The person object is modified via the reference from the anotherPerson precisely the age which is changed from 25 to 30. As seen in the output, the original object changes after the modification hence the object is said to be mutated. <!DOCTYPE html> <html> <body> <h2>JavaScript Reference Types Example: Object Mutability</h2> <script> // Create an object const person = { name: “John”, age: 25 }; // Create a reference to the object let anotherPerson = person; // Display the original object document.write(“<p>Original Object: ” + JSON.stringify(person) + “</p>”); // Modify the object through the reference anotherPerson.age = 30; // Display the modified object document.write(“<p>Modified Object: ” + JSON.stringify(person) + “</p>”); // Both references point to the same object, so changes are reflected in both document.write(“<p>Original Object after modification through reference: ” + JSON.stringify(person) + “</p>”); </script> </body> </html> Example 2: Array Modification Arrays which can store multiple values of different data types in JavaScript inside of a single variable are demonstrated here. They exhibit mutability which means then when a reference is made to an array, changes made to the reference also reflect in the original array. Here we create an array of colors and modify it through the reference of moreColors, mainly by pushing an element “yellow”. <!DOCTYPE html> <html> <body> <h2>JavaScript Reference Types Example: Array Modification</h2> <script> // Create an array const colors = [“red”, “green”, “blue”]; // Create a reference to the array let moreColors = colors; // Display the original array document.write(“<p>Original Array: ” + JSON.stringify(colors) + “</p>”); // Modify the array through the reference moreColors.push(“yellow”); // Display the modified array document.write(“<p>Modified Array: ” + JSON.stringify(colors) + “</p>”); // Both references point to the same array, so changes are reflected in both document.write(“<p>Original Array after modification through reference: ” + JSON.stringify(colors) + “</p>”); </script> </body> </html> Example 3: Function Reference Type In this example, we create a function greet whose reference is initially assigned to greetingFunction. After using it to say Hello, we modify the reference to point to a different function which greets with Hola. This demonstrated the flexibility of function references in JavaScript. <!DOCTYPE html> <html> <body> <h2>JavaScript Reference Types Example: Function Invocation</h2> <script> // Create a function function greet(name) { return “Hello, ” + name + “!”; } // Create a reference to the function let greetingFunction = greet; document.write(“<p>Original Function Result: ” + greetingFunction(“John”) + “</p>”); greetingFunction = function(name) { return “Hola, ” + name + “!”; }; document.write(“<p>Modified Function Result: ” + greetingFunction(“Maria”) + “</p>”); </script> </body> </html> Example 4: Custom class This example demonstrated custom classes in JavaScript another crucial aspect from the point of view reference types. The class consists of properties and functions/methods. Here we create a class Book with a constructor and a method. 4 instances of this book class are created namely (book1, book2, book3, book4) and are given the respective data such as title, author and genre. <!DOCTYPE html> <html> <body> <h2>JavaScript Reference Types Example: Custom class</h2> <script> // Define a custom class for Book class Book { constructor(title, author, genre) { this.title = title; this.author = author; this.genre = genre; } // Method to get book details getDetails() { return `Title:
JavaScript – Clickjacking Attack ”; Previous Next Clickjacking Attack An attacker employs clickjacking, a form of cyber-attack, to deceive a user into clicking on an object different from their perception; this deception may result in unintended actions. The attacker achieves this by overlaying invisible elements or frames over valid content thus camouflaging the malicious intent or manipulating the appearance of webpage elements outright. Severe risks such as unauthorized financial transactions, potential data breaches and compromise of sensitive information are posed by clickjacking. Clickjacking impacts users and website owners alike leading to legal consequences, financial loss, and heightened cybersecurity concerns. The deceptive nature of clickjacking can erode user trust with far-reaching consequences in the digital ecosystem. Disclaimer: The contents of this chapter are only for education purposes! How clickjacking works? Overlaying Content The attackers create a malicious/spam/scam website or injects malicious code into a website which is actually legitimate in nature. The attacker positions invisible elements or frames over the legitimate content on the page. These elements can be transparent iframes or other HTML elements. Deceptive Presentation The attacker then entices the user to interact with the visible elements on the page, which are typically buttons, links, or forms. However, these visible elements are actually on top of the invisible, malicious elements. User Interaction When the user interacts with the visible elements (clicking, typing, etc.), they are unknowingly interacting with the hidden, malicious elements that are overlaid on top of the legitimate content. Unintended Actions The attacker can manipulate the hidden elements to perform unintended actions on behalf of the user. This could include making unwanted transactions, changing account settings, or even submitting sensitive information. User Unawareness Because the user believes they are interacting with the visible elements they see, they remain unaware that their actions are being redirected to perform malicious activities. Examples Example 1: Button Overlay The provided HTML code demonstrates a button overlay clickjacking example. The button is presented to the user, but it is actually overlaid on a hidden, malicious iframe, leading the user to a potentially harmful page. home.html <!DOCTYPE html> <html> <body> <h2>This is content of the home page</h2> <iframe src=”legitimate-site.html” width=”100%” height=”100%”></iframe> <div> <button onclick=”window.location.href=”malicious-site.html””>Click Me</button> </div> </body> </html> legitimate-site.html <!DOCTYPE html> <html> <body> <header> <h1>Welcome to Legitimate Site</h1> </header> <section> <p>This is a legitimate website. You can trust the content here.</p> </section> <footer> <p>© 2024 Legitimate Site. All rights reserved.</p> </footer> </body> </html> malicious-site.html <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; } .danger-sign { color: red; font-size: 2em; } .warning-message { color: red; font-weight: bold; } </style> </head> <body> <header> <h1 class=”danger-sign”>⚠️ Danger: Malicious Site</h1> </header> <section> <p class=”warning-message”>This website has been identified as potentially harmful. Visiting it may pose a security risk to your computer and personal information.</p> </section> <footer> <p>Please close this page immediately and do not proceed.</p> </footer> </body> </html> Output Example 2 When the webpage loads in this example, it initiates an automatic click on a button identified as “clickMe.” This specific button, upon receiving user interaction by means of clicking, activates a JavaScript event that re-routes the user to a potentially harmful site named ”malicious-site.html.” Such covert manipulation disconcertingly guides users towards unintended destinations without their knowledge or consent. Always note: these practices are indeed, potentially harmful and unethical in nature; one must approach them with responsibility and within legal and ethical boundaries. The malicious-site.html code is same as above. home.html <!DOCTYPE html> <html> <head> <style> body { display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; } button { position: absolute; z-index: 1; background-color: transparent; border: none; font-size: 20px; cursor: pointer; } </style> </head> <body onload=”myFunction()”> <h2>Your Content Goes Here</h2> <button id=”clickMe”>Click Me</button> <script> window.onload = function() { var button = document.getElementById(“clickMe”); button.click(); }; document.getElementById(“clickMe”).addEventListener(“click”, function() { window.location.href = “malicious-site.html”; }); </script> </body> </html> Output Real World Clickjacking Incidents 1. Facebook “Like” Button (2011) Attackers overlaid a malicious “Like” button on an enticing video thumbnail, tricking users into unknowingly liking a malicious page. 2. Adobe Flash Update Scam (2015): Malicious buttons disguised as Adobe Flash updates were overlayed on legitimate websites, leading users to unwittingly download malware. 3. Twitter Clickjacking Attack Malicious links on Twitter, disguised as enticing content, led users to unintentionally retweet and spread malicious content. 4. LinkedIn Fake Connection Requests Clickjacking was used to trick LinkedIn users into connecting with fake profiles by overlaying connection request buttons on seemingly innocent content. 5. Google Play Store Deception Malicious overlays on the Google Play Store tricked users into unintended downloads or actions, often related to ads. Preventive Measures 1. X-Frame-Options Header Set the X-Frame-Options header to DENY or SAMEORIGIN in your web server”s response to prevent your site from being embedded in iframes. 2. Frame-Busting Scripts Implement frame-busting scripts in your web pages to prevent them from being embedded in iframes. 3. Content Security Policy (CSP) Use Content Security Policy headers to control the sources from which your website can load content, reducing the risk of clickjacking. 4. User Education Educate users about potential risks associated with interacting with unfamiliar or suspicious-looking content. As cybersecurity evolves, future trends in clickjacking may include more sophisticated techniques leveraging artificial intelligence, increased use of social engineering tactics, and a focus on bypassing advanced security measures. Additionally, with the rise of emerging technologies like augmented reality (AR) and virtual reality (VR), new vectors for immersive clickjacking experiences may emerge, demanding continuous innovation in defensive strategies and user awareness. Print Page Previous Next Advertisements ”;