Event Attributes

Inline Event Handlers

Example

Attributes like onclick, onchange and oninput run JavaScript when something happens:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<button onclick="this.textContent = 'Clicked!'">Click me</button>
<p>Type your name: <input oninput="document.getElementById('out').textContent = 'Hello, ' + this.value"></p>
<p id="out"></p>

</body>
</html>

Result

Prefer addEventListener

Inline handlers mix behaviour into HTML and are blocked by strict Content Security Policies. In real projects, attach events from your script file:

<button id="save">Save</button>
<script>
  document.getElementById('save').addEventListener('click', () => {
    console.log('Saved');
  });
</script>

Events are covered in depth in the JavaScript course (DOM Manipulation).