To add JavaScript to HTML files, you will use an HTML element tag called a script.
A script tag is a tag that lets you insert JavaScript code in the HTML file. Another purpose of a script tag is to link a JavaScript file to an HTML file.
In this example, you’ll write a JavaScript code right inside the HTML file and run it on the browser.
A code example
We will make a simple program that will greet you when clicking the button.
In the HTML file, create the button and add the onclick
attribute to it with the value of greetings()
. The onclick
attribute will run JavaScript when the button is clicked.
<button onclick="greetings()">Click me!</button>
Next, add the script
tag under the button, and inside the script tags, create a function called greetings. In the function brackets, add the alert()
method.
You can write whatever you want inside the alert bracket. I add “Hi, I’m JavaScript!” as a demo.
<script>
function greetings() {
alert("Hi, I'm JavaScript!");
}
</script>
If you followed the steps above, this is how the code should look like:
<button onclick="greetings()">Click me!</button>
<script>
function greetings() {
alert("Hi, I'm JavaScript!");
}
</script>
An output example
Now you are ready to run JavaScript in an HTML file. Go to the browser and click the button. A message will pop up saying, “Hi, I’m JavaScript!”.
With this, you have learned how to add JavaScript to HTML today.
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript