In HTML, a script is a small, embedded program that can add interactivity to your website. For example, a script could generate a pop-up alert box message, or provide a dropdown menu.
Because HTML doesn't actually have scripting capability, you need to use the
<script> element to declare a script, using a scripting language.
The opening and closing
<script> tags tell the browser to expect a script in between them. You can specify the language using the
Adding a Script
Scripts are often placed within the
<head> element. This ensures that the script is ready to run when it is called.
However, this is not a requirement, and you can also place it within the
<body> element if needed.
In fact, it's often a good idea to place them at the bottom of the page, just before the closing
</body> tag, as long it comes before any other scripts that might rely on it.
Placing that code alone into an HTML page would result in a pop-up message as soon as the page loads. Click the button to see it run.
Triggering a Script
In many cases, you won't want the script to run automatically. You might only want the script to run if the user does something (like hovers over, or clicks a link), or once the page has finished loading.
These actions are called intrinsic events (events for short). There are many pre-defined intrinsic events that can trigger a script to run. You use event handlers to tell the browser which event should trigger which script. These are specified as an attribute within the HTML tag.
Lets say you want a message to be displayed whenever a user clicks a button. You can use the
onclick event handler is one of may event handlers available in HTML. There are event handlers for things like mouseovers, page loads, form changes, and more.
Here's the full list of event handlers available in HTML for that you can use as a reference.
Calling an External Script
You can also place your scripts into their own file, then call that file from your HTML document. This is useful if you want the same scripts available to multiple HTML documents - it saves you from having to "copy and paste" the scripts into each HTML document. This makes it much easier to maintain your website.
Alternate Information for Older Browsers