Introduction to JavaScript Events

JavaScript events are actions or occurrences that happen in the browser, which can be detected and responded to by JavaScript code. Events allow web pages to become interactive by responding to user actions.

Basic Concept

When an event occurs, the browser creates an event object containing details about the event, and then triggers any event handlers (functions) that are listening for that event.

Try It Out

Click the button below to see an event in action:

Event log will appear here...

Event Types

JavaScript supports many different event types. Here are some of the most common categories:

Mouse Events

click - Element is clicked

dblclick - Element is double-clicked

mouseenter - Mouse pointer moves into an element

mouseleave - Mouse pointer moves out of an element

Keyboard Events

keydown - Key is pressed down

keyup - Key is released

keypress - Key is pressed (deprecated)

Form Events

submit - Form is submitted

change - Input value changes

focus - Element gains focus

blur - Element loses focus

Event Handling Methods

There are several ways to handle events in JavaScript:

Inline HTML Event Handlers

<button onclick="handleClick()">Click me</button>

<script>
function handleClick() {
    alert('Button was clicked!');
}
</script>

DOM Property Event Handlers

const button = document.getElementById('myButton');

button.onclick = function() {
    alert('Button was clicked!');
};

addEventListener() (Recommended)

const button = document.getElementById('myButton');

button.addEventListener('click', function(event) {
    alert('Button was clicked!');
});

The Event Object

When an event occurs, the browser creates an event object containing information about the event. This object is passed as an argument to the event handler.

element.addEventListener('click', function(event) {
    console.log('Event type:', event.type);
    console.log('Target element:', event.target);
    console.log('Mouse coordinates:', event.clientX, event.clientY);
    console.log('Key pressed:', event.key); // For keyboard events
    event.preventDefault(); // Prevent default behavior
    event.stopPropagation(); // Stop event bubbling
});

Try It Out

Click anywhere in this box to see event object properties:

Click here to see event details

Event Propagation

Event propagation determines the order in which elements receive the event. There are two phases: bubbling (default) and capturing.

Event Bubbling

// When the inner element is clicked, the event bubbles up
outer.addEventListener('click', function() {
    console.log('Outer element clicked');
});

inner.addEventListener('click', function() {
    console.log('Inner element clicked');
});
// Clicking inner will log: "Inner element clicked", then "Outer element clicked"

Event Capturing

// Use the third parameter to enable capturing
outer.addEventListener('click', function() {
    console.log('Outer element clicked');
}, true);

inner.addEventListener('click', function() {
    console.log('Inner element clicked');
}, true);
// Clicking inner will log: "Outer element clicked", then "Inner element clicked"

Event Delegation

Event delegation uses event bubbling to handle events at a higher level in the DOM rather than on individual elements.

// Instead of adding listeners to each list item
document.getElementById('myList').addEventListener('click', function(event) {
    if (event.target.tagName === 'LI') {
        console.log('List item clicked:', event.target.textContent);
    }
});

Try It Out

Click on any item in the list below (even dynamically added ones):

  • Item 1
  • Item 2
  • Item 3

Practical Examples

Form Validation

const form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent form submission
    
    const email = document.getElementById('email').value;
    
    if (!isValidEmail(email)) {
        showError('Please enter a valid email address');
        return;
    }
    
    // Form is valid, proceed with submission
    this.submit();
});

Keyboard Shortcuts

document.addEventListener('keydown', function(event) {
    // Ctrl + S to save
    if (event.ctrlKey && event.key === 's') {
        event.preventDefault();
        saveDocument();
    }
});