In HTML, JavaScripts must be inserted between <script> and </script> tags.
JavaScripts can be put in the <body> and in the <head> section of an HTML page.
The <script> Tag
To insert a JavaScript into an HTML page, use the <script> tag.
The <script> and </script> tells where the JavaScript starts and ends.
The lines between <script> and </script> contain the JavaScript code:
Example
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "My First JavaScript Function";
}
</script>
You don't have to understand the code above.
Just take it for a fact, that the browser will interpret the code between the <script> and </script> tags as JavaScript.
Note Old examples may have type=”text/javascript” in the <script> tag. This is no longer required.
JavaScript is the default scripting language in all modern browsers and in HTML5.
JavaScript Functions and Events
Often, JavaScript code is written to be executed when an event occurs, like when the user clicks a button.
JavaScript code inside a function, can be invoked later, when an event occurs.
Invoke a function = Call upon a function (ask for the code in the function to be executed).
You will learn much more about functions and events in later chapters.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body> or in the <head> section of HTML, and/or in both.
Often you will see scripts at the bottom of the <body> section of a web page. This can reduce display time.
Sometimes you will see all JavaScript functions in the <head> section.
Anyway, separating HTML and JavaScript, by putting all the code in one place, is always a good habit.