HTML Event Attributes

Event attributes let you run JavaScript directly in response to something happening on an element — a click, a key press, a page load, a form submission. They are written as plain HTML attributes whose name always begins with on, followed by the event name, e.g. onclick, onchange, onload.

1) Mouse Events


<button onclick="alert('Button clicked!')">Click me</button>

<div onmouseover="this.style.background='yellow'"
     onmouseout="this.style.background=''">
  Hover over me
</div>

onclick fires on a mouse click (or tap), onmouseover fires when the pointer enters an element, and onmouseout fires when it leaves.

Live demo — click the button, then hover over the box:

Clicked 0 time(s).

Hover over this box to see onmouseover / onmouseout in action.

2) Keyboard Events


<input type="text"
       onkeydown="console.log('key going down')"
       onkeyup="console.log('key released')">

onkeydown fires the moment a key is pressed down, and onkeyup fires when it is released. These are commonly used for live character counters, keyboard shortcuts, and simple input filtering.

3) Form Events


<form onsubmit="return validateForm()">
  <input type="text" name="username"
         oninput="console.log('typing...')"
         onfocus="this.style.borderColor='blue'"
         onblur="this.style.borderColor=''">

  <select onchange="console.log('selection changed')">
    <option>A</option>
    <option>B</option>
  </select>

  <button type="submit">Submit</button>
</form>

  • onsubmit — fires when a form is submitted; returning false cancels submission.
  • onchange — fires when a control's value changes and the element loses focus (typical for <select>, checkboxes, and finalized text input).
  • oninput — fires immediately on every keystroke or value change, without waiting for blur.
  • onfocus / onblur — fire when a control gains or loses keyboard focus.

4) Window & Document Events


<body onload="console.log('page fully loaded')" onresize="console.log('window resized')">

onload fires once the whole page (including images and stylesheets) has finished loading — traditionally placed on <body>. onresize fires whenever the browser window is resized, useful for responsive JavaScript adjustments.

Best Practice: Inline event attributes like onclick="..." are fine for quick demos and learning, but production code should prefer JavaScript's addEventListener() instead. It keeps HTML and behaviour separate, allows multiple listeners on the same event, and avoids the security and maintainability issues already covered in the HTML Best Practices page.