JavaScript Mouse, Scroll, Touch, and Drag Events

This tutorial explains the core DOM events used to handle user interactions. You’ll find syntax examples, explanations, and an interactive demo.

1. Mouse Events

Mouse events are triggered by user interactions using a mouse. You can detect clicks, hovering, scrolling, and button states.

Common Mouse Events:

Example - Adding New Cards on Click:


card.addEventListener('click', () => {
    const newCard = document.createElement('div');
    newCard.classList.add('card');
    newCard.innerText = count++;
    container.appendChild(newCard);
});
        

2. Scroll Events

The scroll event occurs when an element is scrolled. Use it carefully as it can trigger multiple times rapidly.

Key Notes:

Example:


window.addEventListener('scroll', (e) => {
    console.log("Page is scrolling", e);
});
        

3. Touch Events (Mobile)

Touch events work on mobile or touch-enabled devices. They allow developers to handle finger gestures.

Touch Event Types:

Example:


card.addEventListener('touchstart', (e) => {
    console.log("Touch started", e);
});
        

4. Drag Events

Drag events are used for drag-and-drop features. They involve moving an element and optionally dropping it elsewhere.

Key Drag Events:

Example:


card.addEventListener('dragstart', (e) => {
    console.log("Drag started", e);
});
card.addEventListener('drag', (e) => {
    console.log("Dragging...", e);
});
card.addEventListener('dragend', (e) => {
    console.log("Drag ended", e);
});