JavaScript Events

Events let your page react to user actions like clicks, typing, and form submits. Prefer using addEventListener instead of inline HTML attributes.

1) Inline Handler (onclick)

Quick but not recommended for larger apps (mixes HTML and JS).


<!-- HTML -->
<button onclick="alert('Clicked!')">Click me</button>

2) addEventListener (Recommended)

Separate JS from HTML, attach multiple listeners, and remove when needed.


<!-- HTML -->
<button id="btn">Click</button>

<!-- JS -->
const btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  alert('Clicked!');
});

3) The Event Object

Every handler receives an event object with details about the action.


btn.addEventListener('click', function(e) {
  console.log('type:', e.type);           // "click"
  console.log('target id:', e.target.id);  // "btn"
});

4) Prevent Default

Stop default browser behavior (e.g., following a link, submitting a form).


<!-- HTML -->
<a href="https://example.com" id="go">Go</a>

<!-- JS -->
document.getElementById('go').addEventListener('click', function(e) {
  e.preventDefault(); // stop navigation
  alert('Link blocked');
});

5) Keyboard Events

Listen for keys: keydown, keyup. Use e.key to know which key.


document.addEventListener('keydown', function(e) {
  console.log('Pressed:', e.key);
});

6) input & change Events

input fires as you type; change fires when field loses focus or value is committed.


<!-- HTML -->
<input id="name" placeholder="Type...">

<!-- JS -->
const inp = document.getElementById('name');
inp.addEventListener('input', e => {
  console.log('Now:', e.target.value);
});
inp.addEventListener('change', e => {
  alert('Final value: ' + e.target.value);
});

7) DOMContentLoaded

Run JS after the HTML is parsed (elements exist in the DOM).


document.addEventListener('DOMContentLoaded', function() {
  console.log('DOM ready');
});

8) Event Delegation

Attach one listener on a parent and handle events from its children via e.target.


<!-- HTML -->
<ul id="list">
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>

<!-- JS -->
document.getElementById('list').addEventListener('click', function(e) {
  if (e.target.tagName === 'LI') {
    alert('You clicked: ' + e.target.textContent);
  }
});
Tip: Prefer addEventListener, clean up with removeEventListener when needed, and debounce/throttle frequent events (like scroll or input) for performance.