JavaScript (JS) is a programming language mainly used alongside HTML and CSS to make websites interactive and add functionality to static web pages by making them more dynamic.
There are two main ways to add JavaScript code to an HTML file. They are as follows:
<script>
tags. Let's explore the syntax and a code example to understand how we can use <script>
tags to add JS to HTML.
Note:
<script>
tags allow us to place the JavaScript code anywhere in the HTML file, such as in the<head>
and<body>
sections of the HTML document.
Here's the syntax needed to incorporate JS using inline HTML:
//All JS code must be wrapped using the script tags
<script>
alert('Welcome to educative answers');
</script>
This code snippet below uses the syntax mentioned above:
<img>
tag to render the image as seen in the output tab.<div>
. This will be populated using the JavaScript code that is defined in the <script>
tag after the user clicks on the button
element present on line 8.<button>
tag, which listens for the onclick
event and fires the changecontent()
method.<script>
tag. We also use the document.getElementById()
to get hold of the <div>
and populate it using the innerHTML
property as specified in the widget above. To explore more on
document.getElementById()
and theinnerHTML
property of JS, please refer to the following links:
Another way to add JS to an HTML file is to link the external JS file with the <script>
tag of our HTML file.
The only difference between this method and the one mentioned above is that the JS code now resides in a separate file. This makes it easier to maintain. Moreover, JS files are supported by all modern-day browsers and are often cached, loading the web pages quickly.
To import the JS file into HTML, we still have to use the <script>
tag but in a different way specified as the following:
<script src='file_path'></script>
The src
attribute in the syntax above is used to specify the path to the JS file.
The code widget below illustrates how we can reference a JS file present locally in our directory:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div class='div-container'> <p><img src='./logoMarkv2.png'></p> <div id='content'></div> <button type="button" onclick="changecontent()">Click me to reveal the name!</button> </div> <script src='script.js'></script> </body> </html>
The code now is only maintained in different files and is linked to index.html
. Only line 12 is changed in the HTML file.
<script>
tag with the src
attribute to import the JS code as specified in the script.js
file.Note: This method can also be used to reference files which are present on the internet as specified in the
src
attribute of the<script>
tag.