InterviewSolution
| 1. |
How to create a Cookie with JavaScript? |
|
Answer» The following are the different ways in which we can include JavaScript code in an HTML file. We can add JavaScript in the same file or an external file: Java Script in the same file Add the JavaScript code in the same HTML file using any of the following ways: In head section If you want the script to run on some event, then add the JavaScript code in the head section of the HTML file. Let us see an example: <html> <head> <script> <!-- function show() { alert("Demo!") } //--> </script> </head> <body> <input type="button" onclick="show()" value="Click" /> </body> </html>In body section If you want the script to run on page load, then add the JavaScript code in the body section of the HTML file. Let us see an example: <html> <head> </head> <body> <script> <!-- document.write("Demo") //--> </script> <p></p> </body> </html>JavaScript in an external file Using the <script> TAG you can STORE the JavaScript code in an external .JS extension file. The tag with the “src” attribute allows you to include this js file in your HTML. If you are using the same JavaScript code in almost every page, then it’s a good practice to create an external JS file and include it in HTML of every page. This enhances the loading time. Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the <script> tag. The src attribute is used to include the external JavaScript file in your HTML: <script src="myfile.js" ></script>Let’s say the following is the content of our external JS file “myfile.js”: function show () { alert("Learning is fun!"); }The following is our HTML file, wherein we will include the external file “myfile.js”: <html> <body> <form> <input type="button" value="Click" onclick="show()"/> </form> <script src="show.js"> </script> </body> </html>Press the button “Click”: On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function: |
|