Attaching JavaScript to HTML

As with CSS there are a number of ways to include JavaScript in HTML pages.

  1. As with CSS, JavaScript can be saved as an external file and linked into the head of a HTML page.

    <script type="text/javascript" src="script.js"></script>
    
  2. Also as with CSS, JavaScript can be included in HTML using the <script> tag. Unlike CSS JavaScript can be included anywhere in the HTML document.

    <script type="text/javascript">
    	alert('This is an alert triggered by JavaScript');
    </script>
    
  3. JavaScript can be targetted by HTML hyperlinks by replacing the value of the href attribute with javascript: (some JavaScript). Doing this is not very good practice as people without JavaScript enabled web browsers will only see dead links.

    <a href="javascript:alert('JavaScript Alert!');">Run Alert</a>
    
  4. JavaScript can be triggered by event handler attributes added to HTML tags. Event handlers respond to actions the user makes on the web-page. The example below will trigger when the user clicks on the text Click Me.

    <div onclick="alert('JavaScript Alert!');">Click Me</div>