A script is a small piece of program which is used to make the web page more interactive, dynamic and attractive. Currently, JavaScript is mostly used as a scripting language for webpages. JavaScript is used with HTML to make more interactive webpages.
Example:
<p id="trial"></p>
<button type="button"
onclick="document.getElementById('trial').innerHTML = Date()">
Click here to display Date and Time. </button>
You can add javaScript code in a separate file and then include it whenever it is needed or you can define functions inside the HTML document itself. Let’s see both the cases of adding JavaScript.
External JavaScript:
If you are going to define a functionality that will be used in various HTML documents then it is better to keep that JavaScript functionality in a separate file and then include that file in your documents. A JS file will have extension as .js and it will be included in HTML file using <script> tag.
Following is the external JS file with script.js name.
function Hello() {
alert("Hello, World");
}
Following example uses above external JS file.
Example:
<!DOCTYPE html>
<html>
<head>
<title> External JavaScript </title>
<script src = "/html/script.js" type = "text/javascript"></script>
</head>
<body>
<input type = "button" onclick = "Hello();" name = "ok" value = "Click Here">
You can write JS code directly into your HTML document. Generally, we keep JS script code in the header of the document using <script> tag, otherwise, there are no restrictions you can put your JS code anywhere in the document but inside the <script> tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title> Internal JavaScript </title>
<script type = "text/JavaScript">
function Hello() {
alert("Hello, World");
}
</script>
</head>
<body>
<input type = "button" onclick = "Hello();" name = "ok" value = "Click Here">
The <script> tag in HTML is used to specify client-side script. The <script> tag either contains the statements to be a script or it points to an external script file through src attribute. JavaScript is mainly used for image manipulation, form validation and to change content dynamically. The document.getElementById() method is used by JS to select an HTML element. You can place <script> tag in the <body> section or <head> section.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok