HTML scripts are used to add dynamic functionality to HTML pages by allowing you to include executable code in the web page. In this tutorial, we’ll cover the basics of HTML scripts and how to use them to add dynamic features to your web pages.
An HTML script is a block of code that is written in a programming language such as JavaScript or VBScript and is embedded in an HTML page. HTML script are executed by the browser when the page is loaded or when a specific event occurs, such as a button click.
To add an HTML script to your page, you need to include it within the <script>
tags.
There are two ways to add a script to your page:
Inline scripts are included directly in the HTML document using the <script>
tag. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script>
// JavaScript code goes here
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
In the above example, we have included an inline script block in the <head>
section of the HTML document.
External scripts are stored in separate files with a .js file extension and are linked to the HTML document using the <script>
tag’s “src” attribute. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src="myscript.js"></script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
In the above example, we have linked an external script file named “myscript.js” to our HTML document.
Here’s the basic syntax of an HTML script:
<script>
// JavaScript code goes here
</script>
HTML scripts can be used to handle events such as button clicks, form submissions, and page loads. To handle an event, you need to add an event listener to the HTML element using JavaScript. Here’s an example of how to handle a button click event:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello World!</h1>
<button id="myButton">Click me!</button>
<script>
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
</body>
</html>
In the above example, we have added an event listener to the button element using JavaScript. When the button is clicked, an alert box will appear with the message “Button clicked!”
HTML scripts are a powerful tool for adding dynamic functionality to your web pages. By using HTML script, you can create interactive web pages that respond to user input and provide a better user experience.
Sign in to your account