HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Events

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, it can react to these events (e.g., a button being clicked, a page loading, or a mouse moving).


Assigning Events

There are two primary ways to assign events using the basic DOM model:

1. Using HTML Attributes

The simplest way is adding an event attribute directly to the HTML tag.

<button onclick="displayDate()">Click Me</button>

2. Using Object Properties

A cleaner way is assigning the event to an element's property in your JavaScript file.

document.getElementById("myBtn").onclick = displayDate;

Common HTML Events

Here are some of the most frequently used events in web development:

  • onclick: The user clicks an element.
  • onchange: An HTML element has been changed (often used in inputs/dropdowns).
  • onmouseover / onmouseout: The user moves the mouse over / away from an element.
  • onkeydown: The user pushes a keyboard key.
  • onload: The browser has finished loading the page.

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page. They are often used to initialize variables or handle cookies.

<body onload="checkCookies()">

The onmouseover and onmouseout Events

These events can be used to create interactive hover effects without using CSS :hover, allowing for more complex logic.

<div onmouseover="mOver(this)" onmouseout="mOut(this)">Hover Me</div>
Technical Note: When assigning event properties in JS (Method 2), never use parentheses for the function name (e.g., use onload = check; not onload = check();).

Key Points to Remember

  • Events allow JavaScript to interact with user behavior
  • Use the this keyword inside an event handler to refer to the current element
  • onchange is vital for validating search boxes and form inputs
  • onload is used to check the user's browser type or version
  • Events can be assigned in HTML or in Script files
  • The next lesson will introduce addEventListener, the modern way to handle events