#javascript #tutorial #beginner

Day 6: Events & Interactive UI

Day 6: Events

JavaScript is event-driven. Code usually runs in response to something happening (a click, a keystroke, a timer).

1. Event Listeners

Use addEventListener to “listen” for an event on an element.

const button = document.querySelector('button');

button.addEventListener('click', () => {
    alert('Button Clicked!');
});

Common Events:

  • click, dblclick
  • mouseenter, mouseleave (Hover)
  • keydown, keyup (Keyboard)
  • submit (Forms)
  • input (Typing in a text field)

2. The Event Object (e)

The callback function receives an event object with details about what happened.

const input = document.querySelector('input');

input.addEventListener('keyup', (e) => {
    console.log(e.key); // Which key was pressed?
    console.log(e.target.value); // current text in input
});

3. Preventing Default Behavior

Some elements have default actions (e.g., forms reload the page on submit). You often want to stop this.

const form = document.querySelector('form');

form.addEventListener('submit', (e) => {
    e.preventDefault(); // Stop page reload
    console.log("Form submitted via JS!");
});

4. Event Bubbling

If you click a button inside a div, the click event fires on the button first, then “bubbles up” to the div.

div.addEventListener('click', () => console.log('Div clicked'));
btn.addEventListener('click', (e) => {
    e.stopPropagation(); // Stop the bubble!
    console.log('Button clicked');
});

Homework for Day 6:

  1. Create a button “Counter”.
  2. Create a variable count = 0.
  3. Every time the button is clicked, increment count and update the text of a <span> to show the new number.

Day 7: We level up with Modern ES6+ Syntax!