In HTML, JavaScript code is inserted between <script> and </script> tags. For example:
Try it yourself
Output |
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that is executed when called for or when an event occurs. Like, when a user clicks a button.
We'll discuss more about it in later chapter. Here we are using a common function to make convenient our programs to run.
We'll discuss more about it in later chapter. Here we are using a common function to make convenient our programs to run.
JavaScript in Head section of HTML document.
See the below example, here JavaScript (element between <Script> and </Script>) is used under head section.
See the below example, here JavaScript (element between <Script> and </Script>) is inserted under Body section.
Scripts can also be saved in a separate file and kept externally, so that whenever it will be needed, can be inserted in HTML document. It is useful when same JavaScript code is used with many HTML pages.
When we save JavaScript file, its extension should be '.js'.
To use the external JavaScript file put the name of that file with src (source) attribute in <script> tag.
To use the external JavaScript file put the name of that file with src (source) attribute in <script> tag.
Making of External JavaScript file.
Type the following codes in text editor
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
Now save it with the name 'my Javascript.js'.
Now put the name of the JavaScript file in an HTML page as follows:
Try yourself
Output |
Advantages of External Javascript:
TOP
i. Due to an external Javascript, we can keep HTML and Javascript file Seperate.
ii. The seperate files help us to easily understand both HTML and Javascript as well as maintain both the languages.
External Javascript can be referenced in three different ways:
i. By using the "file name' only.
ex. <script src = "myJavaScript.js"> </script>
ii. By using the path of the file.
ex.<script src = "c/yashi/onedrive/desktop/myJavaScript.js"> </script>
iii. By using the complete url.
ex.<script src = "https://www.compeducational.com/javascript/myJavaScript.js"> </script>
TOP