HTML Scripts

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 type attribute. However, this is optional if you're using JavaScript, as JavaScript is the default value. JavaScript is also the most popular scripting language used on websites.

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.

Try 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 to perform an action. In this example, we'll display a JavaScript alert box containing a message.

Try it

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

You can provide alternative information for non-JavaScript browsers or browsers with JavaScript disabled. You can do this using the <noscript> tag.

Any contents provided between the opening and closing tag is displayed to the user — but only when JavaScript is disabled.

HTML Code: