HTML Scripts

A script is a small piece of program that is embedded in web pages to make them dynamic and interactive. For example, with scripts you can create a dropdown menu, pop-up box message, etc. The most popular scripting language used on websites is JavaScript.

How to Add Scripts

The <scripts> element is used to embed script or reference to an executable script within an HTML document. Scripts are usually nested within the <head> element to ensure that the script is ready to run when it is called. However, there is no restriction, and the script could be placed anywhere in the document.

If you need the same scripts to be available for many web pages, then you should place scripts into a separate file, then call it from HTML document.

Example

<script type="text/javascript" src="scripts.js"></script>

How to Trigger Scripts

You can specify whether to make a script run automatically (as soon as the page loads), or after the user has done something (like hovering over or clicking a link). If you want the script to run if the user performs any action (called event) then you should use event handlers to let the browser know, which event is responsible for triggering certain script.

Event handlers are specified as attributes within the HTML tag.

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Event Handler Example</title>
    <script type="text/javascript">
      function myAlert() {
        alert("I am an event handler....");
      	return;
      }
    </script>
  </head>
  <body>
    <span onmouseover="myAlert();">
    Bring your mouse here to see an alert
    </span>
  </body>
</html>

Result

The <noscript> element

Though many modern browsers support JavaScript, there are some older browsers that cannot run the JavaScript code. To provide alternative information for non-JavaScript browsers or browsers with JavaScript disabled use the <noscript> tag. The contents of this tag is displayed to the user only in case if JavaScript is disabled or when the browser doesn’t support JavaScript.

Example

<!DOCTYPE html>
<html>
 <head>
    <title>Title of the documnet</title>
  </head>
  <body>
    <script>
      document.write("My first JavaScript example!")
    </script>
    <noscript>Sorry, your browser does not support JavaScript!</noscript>
    <p>A browser that doesn’t support JavaScript will display the content inside the noscript element.</p>
  </body>
</html>

Result