What is JavaScript?
JavaScript is the programming language of the web.
It can calculate, manipulate and validate data.
It can update and change both HTML and CSS.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.
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 an HTML page, or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
External JavaScript
Scripts can also be placed in external files:
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is located.
External scripts cannot contain <script> tags.
External JavaScript Advantages
Placing scripts in external files has some advantages:
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
Example
<script src="[Link]"></script>
<script src="[Link]"></script>
External References
An external script can be referenced in 3 different ways:
With a full URL (a full web address)
With a file path (like /js/)
Without any path
This example uses a full URL to link to [Link]:
Using file path:
No file path: