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> tag to generate a script, using a scripting language.
<script> tags tell the browser to expect a script in between them. You specify the language using the
Adding a Script
You can specify whether to make a script run automatically (as soon as the page loads), or after the user has done something (like click on a link).
In either case, a generally accepted convention is to place your scripts between the
<head></head> tags. This ensures that the script is ready to run when it is called.
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
Be sure to check out this list of HTML 5 event handlers.
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.
Hide Scripts from Older Browsers
Alternate Information for Older Browsers
You can also provide alternative info for users whose browsers don't support scripts (and for users who have disabled scripts). You do this using the
Set a Default Scripting Language
You can specify a default scripting language for all your
script tags to use. This saves you from having to specify the language everytime you use a script tag within the page.
Note that you can still override the default by specifying a language within the script tag.