Showing posts with label JavaScript(Where to put in HTML doc). Show all posts
Showing posts with label JavaScript(Where to put in HTML doc). Show all posts

JavaScript (Where to insert JavaScript code in HTML)

Previous                                                                                     

In HTML, JavaScript code is inserted between <script> and </script> tags. For example: 


Try it yourself
Try it yourself editor
 
Code
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 can place any number of JavaScripts in an HTML document. We can place it in Head section or in Body section or in both places of HTML page.

JavaScript in Head section of HTML document.
See the below example, here JavaScript (element between <Script> and </Script>) is used under head section.


Try yourself Try it yourself editor
 
Code
Output

JavaScript in Body section of HTML document.
See the below example, here JavaScript (element between <Script> and </Script>) is inserted under Body section.

Try yourself Try it yourself editor
 
Code
Output

External JavaScript:
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.

Making of External JavaScript file.
Type the following codes in text editor 
function myFunction() {
  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
Try it yourself editor
 
Code
Output

Advantages of External Javascript:
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

Python: Functions