JavaScript and HTML Events

This video tutorial explains how to run JavaScript code when events occurr on a webpage. Events include clicking an HTML element (such as a button, an image, or some text) or moving the mouse over or away from an element, pressing a key on the keyboard, when an element on the page changes, or when the page has finished loading.

These are the different types of events:

  • onclick (when the mouse clicks an HTML element)
  • onmouseover (when the mouse hovers over an HTML element)
  • onmouseout (when the mouse leaves an HTML element)
  • onkeydown (when a key on the keyboard is pressed)
  • onload (when the page has finished loading)
  • onchange (when an HTML element on the page has changed)

In this example, we will add a button and display an alert message when events occur (clicking on the button or hovering the mouse over a button). We will also display an alert when the page loads.

 

Watch the video below and scroll down for the sample code.

Sample HTML code:

<html>
    <head>
        <title>Events</title>
        <script src="script.js"></script>
    </head>

    <body onload="alert('Hello there!');">
        <button onclick="alert('You clicked me!');">Click me</button>
        <button onmouseover="alert('You hovered.');">Hover over me</button>
    </body>
</html>

JavaScript can also use an event listener in the JavaScript code (instead of HTML code) to ‘listen’ for other events such as the page loading, a user scrolling down the page or the user pressing a keyboard or mouse button. We will look at these event handlers later in this tutorial series.

Next tutorial: Functions

Leave a Reply