JavaScript and TypeScript course ยท Module 8: Events and the DOM

Mouse and Keyboard Events

13 min read ยท
In this lesson5

"In the security systems of Jurassic Park," Ray Arnold shows the large control panel, "we have different types of sensors. Motion detectors react to movement, pressure sensors to touch, sound sensors to noise. Each type requires a different response. In JavaScript, we have a similar situation - different input types require different handling."

Ray points to the monitor and keyboard. "The mouse and keyboard are the two primary sources of user interaction. Each has its own unique events and behaviors."

Mouse Events - The Full Range of Interactions

The mouse generates more than a dozen different event types, from simple clicks to advanced drag gestures. A single click is three signals in a row: mousedown, mouseup, and only then click.

Basic Click Events

The observation area tells a single click from a double click.

const dinosaurViewingArea = document.getElementById('viewing-area');

// click - single click (most popular)
dinosaurViewingArea.addEventListener('click', (event) => {
  console.log('Single click in the viewing area');
  console.log('Position:', event.clientX, event.clientY);

  selectDinosaurAtPosition(event.clientX, event.clientY);
});

// dblclick - double click
dinosaurViewingArea.addEventListener('dblclick', (event) => {
  console.log('Double click - zooming in');

  // Note: this does NOT block text selection, which already starts on mousedown
  event.preventDefault();

  zoomInOnDinosaur(event.clientX, event.clientY);
});

The clientX and clientY fields give the cursor position in the window. Note: preventDefault() in dblclick won't block text selection, because selection already starts on mousedown. That's what the CSS user-select: none rule is for.

// auxclick - middle/other button click (not left)
dinosaurViewingArea.addEventListener('auxclick', (event) => {
  if (event.button === 1) {
    console.log('Middle button - opening in new window');
    openInNewWindow(event.target);
  }
});

// contextmenu - right mouse button (context menu)
dinosaurViewingArea.addEventListener('contextmenu', (event) => {
  event.preventDefault(); // Block default menu

  console.log('Right button - custom context menu');
  showCustomContextMenu(event.clientX, event.clientY);
});

function selectDinosaurAtPosition(x, y) {
  console.log(`Checking if a dinosaur is at position (${x}, ${y})`);
  // Selection logic
}

function zoomInOnDinosaur(x, y) {
  console.log(`Zooming in on position (${x}, ${y})`);
  // Zoom logic
}

function showCustomContextMenu(x, y) {
  const menu = document.getElementById('custom-menu');
  menu.style.left = x + 'px';
  menu.style.top = y + 'px';
  menu.style.display = 'block';

  console.log('Context menu displayed');
}

An event.button value of 1 means the middle button, and preventDefault() on contextmenu hides the browser menu, making room for your own.

Mouse Button Events

Between pressing and releasing the button, the drag is in progress, so we remember the starting point.

const controlPanel = document.getElementById('control-panel');

// mousedown - mouse button pressed (before release)
controlPanel.addEventListener('mousedown', (event) => {
  console.log('Mouse button pressed');
  console.log('Which button:', event.button); // 0=left, 1=middle, 2=right

  if (event.button === 0) {
    console.log('Left button - starting drag');
    startDragging(event);
  }
});

// mouseup - mouse button released
controlPanel.addEventListener('mouseup', (event) => {
  console.log('Mouse button released');

  if (isDragging) {
    console.log('Ending drag');
    stopDragging(event);
  }
});

let isDragging = false;
let dragStartX = 0;
let dragStartY = 0;

function startDragging(event) {
  isDragging = true;
  dragStartX = event.clientX;
  dragStartY = event.clientY;

  console.log(`Drag started from position (${dragStartX}, ${dragStartY})`);
}

function stopDragging(event) {
  const deltaX = event.clientX - dragStartX;
  const deltaY = event.clientY - dragStartY;

  console.log(`Dragged by: X=${deltaX}px, Y=${deltaY}px`);

  isDragging = false;
}

The isDragging flag ties both events into one story, and the difference in coordinates tells you how far the cursor moved.

Mouse Movement Events

Cursor movement over the park map is tracked by mousemove, a sensor that fires at every twitch of the mouse.

const parkMap = document.getElementById('interactive-park-map');

// mousemove - mouse movement (CAUTION: very frequent!)
// Use with care - can generate hundreds of events per second

let mouseMoveCount = 0;

parkMap.addEventListener('mousemove', (event) => {
  mouseMoveCount++;

  // Update cursor position
  updateCursorPosition(event.clientX, event.clientY);

  // If dragging, update position
  if (isDragging) {
    updateDragPosition(event.clientX, event.clientY);
  }

  // Log every 10th event (to avoid flooding the console)
  if (mouseMoveCount % 10 === 0) {
    console.log(`Mouse move #${mouseMoveCount}: (${event.clientX}, ${event.clientY})`);
  }
});

function updateCursorPosition(x, y) {
  const coordsDisplay = document.getElementById('mouse-coords');
  if (coordsDisplay) {
    coordsDisplay.textContent = `X: ${x}, Y: ${y}`;
  }
}

function updateDragPosition(x, y) {
  const draggableElement = document.getElementById('draggable');
  if (draggableElement) {
    draggableElement.style.left = x + 'px';
    draggableElement.style.top = y + 'px';
  }
}

That's why the log reaches the console only every tenth event, and the throttling lesson will show you how to tame such avalanches. Now the cursor entering and leaving.

// mouseenter - mouse enters the element's area (doesn't bubble!)
parkMap.addEventListener('mouseenter', (event) => {
  console.log('Mouse entered the park map');
  parkMap.classList.add('mouse-active');
  showMapControls();
});

// mouseleave - mouse leaves the element's area (doesn't bubble!)
parkMap.addEventListener('mouseleave', (event) => {
  console.log('Mouse left the park map');
  parkMap.classList.remove('mouse-active');
  hideMapControls();
});

// mouseover - mouse enters (bubbles - fires for children too!)
parkMap.addEventListener('mouseover', (event) => {
  if (event.target.classList.contains('enclosure-marker')) {
    const enclosureName = event.target.dataset.name;
    console.log(`Hovered over enclosure marker: ${enclosureName}`);
    showEnclosureTooltip(event.target, enclosureName);
  }
});

// mouseout - mouse leaves (bubbles)
parkMap.addEventListener('mouseout', (event) => {
  if (event.target.classList.contains('enclosure-marker')) {
    console.log('Left enclosure marker');
    hideEnclosureTooltip();
  }
});

function showMapControls() {
  const controls = document.getElementById('map-controls');
  if (controls) {
    controls.style.display = 'block';
  }
}

function hideMapControls() {
  const controls = document.getElementById('map-controls');
  if (controls) {
    controls.style.display = 'none';
  }
}

The mouseenter and mouseleave pair doesn't bubble, so it reacts only to the map itself, while mouseover and mouseout bubble up from every child, hence the event.target check.

Practical Example - Drag System

"One of the most useful features," says Ray, "is drag & drop." The first part of the class starts the drag.

class DinosaurCardDragSystem {
  constructor() {
    this.draggedElement = null;
    this.dragOffsetX = 0;
    this.dragOffsetY = 0;
    this.initialize();
  }

  initialize() {
    const cards = document.querySelectorAll('.dinosaur-card');

    cards.forEach(card => {
      card.addEventListener('mousedown', (e) => this.handleDragStart(e));
    });

    document.addEventListener('mousemove', (e) => this.handleDragMove(e));
    document.addEventListener('mouseup', (e) => this.handleDragEnd(e));

    console.log('Drag & drop system initialized');
  }

  handleDragStart(event) {
    this.draggedElement = event.currentTarget;

    const rect = this.draggedElement.getBoundingClientRect();
    this.dragOffsetX = event.clientX - rect.left;
    this.dragOffsetY = event.clientY - rect.top;

    this.draggedElement.style.position = 'fixed';
    this.draggedElement.style.zIndex = '1000';
    this.draggedElement.classList.add('dragging');

    const dinoName = this.draggedElement.dataset.dinoName;
    console.log(`Started dragging card: ${dinoName}`);

    event.preventDefault(); // Prevent text selection
  }

The mousemove and mouseup listeners sit on the document, because a quick move will take the cursor outside the card. Here preventDefault() in mousedown really does block text selection, and getBoundingClientRect() helps work out the grab point.

  handleDragMove(event) {
    if (!this.draggedElement) return;

    const x = event.clientX - this.dragOffsetX;
    const y = event.clientY - this.dragOffsetY;

    this.draggedElement.style.left = x + 'px';
    this.draggedElement.style.top = y + 'px';
  }

  handleDragEnd(event) {
    if (!this.draggedElement) return;

    const dinoName = this.draggedElement.dataset.dinoName;
    console.log(`Finished dragging card: ${dinoName}`);

    // Check if the card was dropped in an appropriate zone
    const dropZone = this.findDropZone(event.clientX, event.clientY);

    if (dropZone) {
      console.log('Card dropped in zone:', dropZone.id);
      this.handleDrop(this.draggedElement, dropZone);
    } else {
      console.log('Card dropped outside zone - returning to original position');
      this.returnToOriginalPosition();
    }

    this.draggedElement.classList.remove('dragging');
    this.draggedElement = null;
  }

The card follows the cursor, and once the button is released the class looks for the zone where the card landed.

  findDropZone(x, y) {
    const dropZones = document.querySelectorAll('.drop-zone');

    for (const zone of dropZones) {
      const rect = zone.getBoundingClientRect();

      if (x >= rect.left && x <= rect.right &&
          y >= rect.top && y <= rect.bottom) {
        return zone;
      }
    }

    return null;
  }

  handleDrop(card, dropZone) {
    console.log('Adding card to drop zone');
    dropZone.appendChild(card);

    // Reset styles
    card.style.position = '';
    card.style.left = '';
    card.style.top = '';
    card.style.zIndex = '';
  }

  returnToOriginalPosition() {
    // Back to the original place - no animation, because position changes cannot be animated.
    // No setTimeout: handleDragEnd sets this.draggedElement to null right after this
    this.draggedElement.style.position = '';
    this.draggedElement.style.left = '';
    this.draggedElement.style.top = '';
    this.draggedElement.style.zIndex = '';
  }
}

// Initialization
const dragSystem = new DinosaurCardDragSystem();

A card dropped inside a zone moves to the new enclosure, and outside of it, it goes back to its place.

Drag and Drop Built into the Browser

The browser also has its own Drag and Drop API. An element with the draggable="true" attribute sends dragstart, and the target zone receives dragover and drop.

// HTML: <div class="dino-item" draggable="true">T-Rex</div>
const dino = document.querySelector('.dino-item');
const zone = document.getElementById('zone-c');

dino.addEventListener('dragstart', (e) => {
  e.dataTransfer.setData('text/plain', dino.textContent);
  dino.classList.add('dragging');
});
dino.addEventListener('dragend', () => dino.classList.remove('dragging'));

zone.addEventListener('dragover', (e) => {
  e.preventDefault(); // without this the zone won't accept the drop
});

zone.addEventListener('drop', (e) => {
  e.preventDefault(); // blocks the default action, e.g. opening a link
  zone.appendChild(dino);
});

The key part is preventDefault() in dragover, because without it dropping is not allowed, and dragend cleans up after every drag.

Keyboard Events - Keyboard Control

"The keyboard," Ray points to the control panel, "is the second key way of interaction. Keyboard shortcuts, navigation, data input."

Basic Keyboard Events

Every key press leaves a full report in the event object.

// keydown - key pressed (repeats when held)
document.addEventListener('keydown', (event) => {
  console.log('=== KEYDOWN ===');
  console.log('Key:', event.key); // 'a', 'Enter', 'ArrowUp', etc.
  console.log('Code:', event.code); // 'KeyA', 'Enter', 'ArrowUp', etc.
  console.log('KeyCode (deprecated):', event.keyCode);
  console.log('Is it a repeat:', event.repeat);
  console.log('Ctrl:', event.ctrlKey);
  console.log('Shift:', event.shiftKey);
  console.log('Alt:', event.altKey);
  console.log('Meta (Cmd/Win):', event.metaKey);
});

// keyup - key released
document.addEventListener('keyup', (event) => {
  console.log(`Key released: ${event.key}`);
});

// keypress - DEPRECATED! Do not use (use keydown instead)
// keypress is deprecated and does not fire e.g. for arrow keys or Escape

event.key is the character or the name of the key, and event.code is the physical key, independent of the keyboard layout. A key that is held down sends more keydown events with event.repeat set to true, and keyup arrives once.

Practical Keyboard Shortcuts

A single listener on the document handles the shortcuts. First saving, searching, and Escape.

// Keyboard shortcut system for the park
document.addEventListener('keydown', (event) => {
  // Ctrl/Cmd + S - Save
  if ((event.ctrlKey || event.metaKey) && event.key === 's') {
    event.preventDefault();
    console.log('Saving park configuration...');
    saveParkConfiguration();
    return;
  }

  // Ctrl/Cmd + F - Search
  if ((event.ctrlKey || event.metaKey) && event.key === 'f') {
    event.preventDefault();
    console.log('Opening dinosaur search');
    openSearchDialog();
    return;
  }

  // Escape - Close all windows
  if (event.key === 'Escape') {
    console.log('Closing all dialog windows');
    closeAllModals();
    return;
  }

We check ctrlKey or metaKey so that the shortcut also works with Cmd on a Mac, and preventDefault() stops the browser from saving the page. Next come the arrows, the space bar, F1, and the digits.

  // Arrows - Map navigation
  const arrowKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
  if (arrowKeys.includes(event.key)) {
    event.preventDefault();

    const direction = {
      'ArrowUp': 'north',
      'ArrowDown': 'south',
      'ArrowLeft': 'west',
      'ArrowRight': 'east'
    }[event.key];

    console.log(`Moving map in direction: ${direction}`);
    moveMap(direction);
    return;
  }

  // Space - Pause/Resume monitoring
  if (event.key === ' ') {
    event.preventDefault();
    console.log('Toggle monitoring pause');
    toggleMonitoringPause();
    return;
  }

  // F1 - Help
  if (event.key === 'F1') {
    event.preventDefault();
    console.log('Opening help');
    openHelp();
    return;
  }

  // Numbers 1-9 - Quick access to enclosures
  if (event.key >= '1' && event.key <= '9') {
    const enclosureNumber = parseInt(event.key);
    console.log(`Switching to enclosure #${enclosureNumber}`);
    jumpToEnclosure(enclosureNumber);
    return;
  }
});

The space bar is named ' ', and the direction map turns an arrow into a compass direction. Then some simple worker functions.

function saveParkConfiguration() {
  console.log('Configuration saved');
}

function openSearchDialog() {
  console.log('Search dialog opened');
}

function closeAllModals() {
  document.querySelectorAll('.modal').forEach(modal => {
    modal.style.display = 'none';
  });
  console.log('All windows closed');
}

function moveMap(direction) {
  console.log(`Map moved in direction: ${direction}`);
}

function toggleMonitoringPause() {
  console.log('Monitoring paused/resumed');
}

function openHelp() {
  console.log('Help opened');
}

function jumpToEnclosure(number) {
  console.log(`Jumping to enclosure #${number}`);
}

The listener recognizes the shortcut, and the logic lives in the functions.

Keyboard Input Validation

A keydown listener can reject a character before it reaches the field: the security code accepts only digits, the phone number also spaces, parentheses, and hyphens, and the name gets a capital letter.

const securityCodeInput = document.getElementById('security-code');
const phoneInput = document.getElementById('phone-number');
const nameInput = document.getElementById('visitor-name');

// Only digits - security code
securityCodeInput.addEventListener('keydown', (event) => {
  // Allow function keys
  const allowedKeys = [
    'Backspace', 'Delete', 'Tab', 'Escape', 'Enter',
    'ArrowLeft', 'ArrowRight', 'Home', 'End'
  ];

  if (allowedKeys.includes(event.key)) {
    return; // Allow
  }

  // Only digits
  if (event.key >= '0' && event.key <= '9') {
    // Maximum 6 digits
    if (securityCodeInput.value.length >= 6 && !event.ctrlKey && !event.metaKey) {
      event.preventDefault();
      console.log('Maximum 6 digits');
    }
    return;
  }

  // Everything else - block
  event.preventDefault();
  console.log('Only digits are allowed');
});

// Phone number formatting
phoneInput.addEventListener('keydown', (event) => {
  const allowedKeys = [
    'Backspace', 'Delete', 'Tab', 'Escape', 'Enter',
    'ArrowLeft', 'ArrowRight', 'Home', 'End'
  ];

  if (allowedKeys.includes(event.key)) return;

  // Only digits, spaces, hyphens, parentheses
  const phoneChars = /^[0-9 ()-]$/;

  if (!phoneChars.test(event.key)) {
    event.preventDefault();
    console.log('Invalid character in phone number');
  }
});

// Auto-capitalize first letter
nameInput.addEventListener('keyup', (event) => {
  const value = nameInput.value;

  if (value.length === 1) {
    nameInput.value = value.toUpperCase();
  }
});

Such a filter is only a convenience, because text can be pasted from the context menu, so check the value on input or submit as well.

Combining Mouse and Keyboard

"The best interfaces," says Ray, "combine both types of input." Modifier keys change the meaning of a click.

const enclosureCards = document.querySelectorAll('.enclosure-card');
let selectedCards = new Set();

enclosureCards.forEach(card => {
  card.addEventListener('click', (event) => {
    const enclosureId = card.dataset.enclosureId;

    // Different behavior depending on modifier keys
    if (event.ctrlKey || event.metaKey) {
      // Ctrl + Click = Toggle selection
      console.log('Ctrl+Click: Toggle selection');

      if (selectedCards.has(enclosureId)) {
        selectedCards.delete(enclosureId);
        card.classList.remove('selected');
      } else {
        selectedCards.add(enclosureId);
        card.classList.add('selected');
      }
    } else if (event.shiftKey) {
      // Shift + Click = Range selection
      console.log('Shift+Click: Range selection');
      selectRange(lastSelected, enclosureId);
    } else {
      // Normal click = Only this one card
      console.log('Normal click: Single selection');

      selectedCards.clear();
      document.querySelectorAll('.enclosure-card.selected').forEach(c => {
        c.classList.remove('selected');
      });

      selectedCards.add(enclosureId);
      card.classList.add('selected');
    }

    lastSelected = enclosureId;
    updateSelectionInfo();
  });
});

let lastSelected = null;

function selectRange(startId, endId) {
  console.log(`Selecting range from ${startId} to ${endId}`);
  // Range selection logic
}

function updateSelectionInfo() {
  console.log(`Selected ${selectedCards.size} enclosures`);
}

Ctrl or Cmd toggles the selection, Shift selects a range, and a plain click leaves a single card. Next, the arrow keys.

// Keyboard navigation through cards
let focusedCardIndex = 0;
const cards = Array.from(enclosureCards);

document.addEventListener('keydown', (event) => {
  // Only when no input field is active
  if (document.activeElement.tagName === 'INPUT') return;

  switch(event.key) {
    case 'ArrowRight':
    case 'ArrowDown':
      event.preventDefault();
      focusedCardIndex = Math.min(focusedCardIndex + 1, cards.length - 1);
      focusCard(focusedCardIndex);
      break;

    case 'ArrowLeft':
    case 'ArrowUp':
      event.preventDefault();
      focusedCardIndex = Math.max(focusedCardIndex - 1, 0);
      focusCard(focusedCardIndex);
      break;

    case 'Enter':
    case ' ':
      event.preventDefault();
      cards[focusedCardIndex].click();
      break;
  }
});

function focusCard(index) {
  cards.forEach(card => card.classList.remove('focused'));
  cards[index].classList.add('focused');
  cards[index].scrollIntoView({ behavior: 'smooth', block: 'nearest' });

  console.log(`Focus on card #${index}: ${cards[index].dataset.enclosureName}`);
}

The activeElement condition doesn't get in the way of typing in fields, and click() on a card runs the same listener as the mouse.

Window and Touch Events

DOMContentLoaded fires when the HTML has been loaded, even though images may still be loading. load on window waits for the whole page with its resources. Scrolling reports scroll, and window.scrollY gives the number of scrolled pixels, so a value larger than before means moving down. On touch screens a finger sends touchstart, touchmove, and touchend in turn, which we'll come back to with gestures.

Summary

"Mouse and keyboard events," Ray summarizes, "are the foundation of interactivity. Just as different sensors in Jurassic Park detect different types of threats, different events allow for diverse user interactions. The key is using the right events for the right tasks."

Key mouse events:

  • click, dblclick, contextmenu - clicks
  • mousedown, mouseup - button control
  • mousemove - position tracking (use carefully!)
  • mouseenter, mouseleave - hovering (don't bubble)
  • mouseover, mouseout - hovering (bubble)

Key keyboard events:

  • keydown - key pressed (use this one)
  • keyup - key released
  • event.key - character/key name ('a', 'Enter', 'ArrowUp')
  • event.code - physical key ('KeyA', 'Enter', 'ArrowUp')
  • Modifier keys: ctrlKey, shiftKey, altKey, metaKey

My advice: base shortcuts on keydown, and moving items between zones on the built-in Drag and Drop. Next lesson: forms.

Remember: every sensor in the park reacts to a different signal, so match the event to the task.

Code for this lesson: index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouse and Keyboard Events - Camera Control</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            margin: 0;
            padding: 20px;
            color: white;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
        }

        .instructions {
            background: rgba(52, 152, 219, 0.2);
            border: 1px solid #3498db;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
        }

        .instructions kbd {
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 8px;
            border-radius: 4px;
            font-family: monospace;
            margin: 0 3px;
        }

        .camera-viewport {
            position: relative;
            width: 100%;
            height: 400px;
            background: linear-gradient(180deg, #34495e 0%, #2c3e50 100%);
            border-radius: 15px;
            overflow: hidden;
            cursor: move;
            margin-bottom: 20px;
            border: 3px solid #7f8c8d;
        }

        .camera-content {
            position: absolute;
            width: 200%;
            height: 200%;
            transition: transform 0.3s ease;
        }

        .dinosaur {
            position: absolute;
            font-size: 60px;
            cursor: pointer;
            transition: transform 0.2s ease;
            user-select: none;
        }

        .dinosaur:hover {
            transform: scale(1.2);
            filter: drop-shadow(0 0 10px rgba(255, 255, 255, 0.5));
        }

        .dinosaur.clicked {
            animation: bounce 0.5s ease;
        }

        @keyframes bounce {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.3); }
        }

        .controls-panel {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .control-box {
            background: rgba(0, 0, 0, 0.6);
            border-radius: 10px;
            padding: 20px;
            border: 1px solid #34495e;
        }

        .control-box h3 {
            margin-top: 0;
            color: #3498db;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .stat-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 10px;
            border-radius: 5px;
        }

        .stat-label {
            color: #bdc3c7;
            font-size: 12px;
        }

        .stat-value {
            color: #ecf0f1;
            font-size: 18px;
            font-weight: bold;
        }

        .arrow-buttons {
            display: grid;
            grid-template-areas:
                ". up ."
                "left . right"
                ". down .";
            gap: 5px;
            justify-content: center;
            align-items: center;
        }

        .arrow-btn {
            width: 60px;
            height: 60px;
            background: linear-gradient(45deg, #3498db, #2980b9);
            border: none;
            border-radius: 10px;
            color: white;
            font-size: 24px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .arrow-btn:hover {
            background: linear-gradient(45deg, #2980b9, #21618c);
            transform: scale(1.05);
        }

        .arrow-btn:active {
            transform: scale(0.95);
        }

        .arrow-btn.up { grid-area: up; }
        .arrow-btn.down { grid-area: down; }
        .arrow-btn.left { grid-area: left; }
        .arrow-btn.right { grid-area: right; }

        .event-log {
            background: rgba(0, 0, 0, 0.8);
            border-radius: 10px;
            padding: 15px;
            max-height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }

        .log-entry {
            padding: 5px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            color: #bdc3c7;
        }

        .log-entry.mouse {
            color: #3498db;
        }

        .log-entry.keyboard {
            color: #e74c3c;
        }

        .log-entry.click {
            color: #f39c12;
        }

        @media (max-width: 768px) {
            .controls-panel {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Camera Control in Jurassic Park</h1>

        <div class="instructions">
            <strong>Controls:</strong> Arrows <kbd>โ†‘</kbd> <kbd>โ†“</kbd> <kbd>โ†</kbd> <kbd>โ†’</kbd> |
            <strong>Pause:</strong> <kbd>Space</kbd> |
            <strong>Zoom:</strong> Double click |
            <strong>Close:</strong> <kbd>Escape</kbd>
        </div>

        <div class="camera-viewport" id="viewport">
            <div class="camera-content" id="camera">
                <div class="dinosaur" style="top: 50px; left: 100px;" data-name="T-Rex">T</div>
                <div class="dinosaur" style="top: 150px; left: 400px;" data-name="Velociraptor">V</div>
                <div class="dinosaur" style="top: 300px; left: 200px;" data-name="Triceratops">Tr</div>
                <div class="dinosaur" style="top: 100px; left: 600px;" data-name="Brachiosaurus">B</div>
                <div class="dinosaur" style="top: 250px; left: 700px;" data-name="Stegosaurus">S</div>
            </div>
        </div>

        <div class="controls-panel">
            <div class="control-box">
                <h3>Statistics</h3>
                <div class="stats">
                    <div class="stat-item">
                        <div class="stat-label">Mouse position</div>
                        <div class="stat-value" id="mouse-pos">0, 0</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Clicks</div>
                        <div class="stat-value" id="click-count">0</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Camera position</div>
                        <div class="stat-value" id="camera-pos">0, 0</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Last key</div>
                        <div class="stat-value" id="last-key">-</div>
                    </div>
                </div>
            </div>

            <div class="control-box">
                <h3>Camera control</h3>
                <div class="arrow-buttons">
                    <button class="arrow-btn up" data-direction="up">โ†‘</button>
                    <button class="arrow-btn left" data-direction="left">โ†</button>
                    <button class="arrow-btn right" data-direction="right">โ†’</button>
                    <button class="arrow-btn down" data-direction="down">โ†“</button>
                </div>
            </div>
        </div>

        <div class="control-box">
            <h3>Event log</h3>
            <div class="event-log" id="event-log"></div>
        </div>
    </div>

    <script>
        // References to elements
        const camera = document.getElementById('camera');
        const viewport = document.getElementById('viewport');
        const mousePosDisplay = document.getElementById('mouse-pos');
        const clickCountDisplay = document.getElementById('click-count');
        const cameraPosDisplay = document.getElementById('camera-pos');
        const lastKeyDisplay = document.getElementById('last-key');
        const eventLog = document.getElementById('event-log');

        // Camera state
        let cameraX = 0;
        let cameraY = 0;
        let clickCount = 0;
        let isPaused = false;
        const moveSpeed = 50;

        // Event logging function
        function logEvent(message, type = 'mouse') {
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            eventLog.insertBefore(logEntry, eventLog.firstChild);

            // Limit number of entries
            if (eventLog.children.length > 20) {
                eventLog.removeChild(eventLog.lastChild);
            }
        }

        // Function that moves the camera
        function moveCamera(direction) {
            if (isPaused) {
                logEvent('Camera paused! Press Space to resume', 'keyboard');
                return;
            }

            switch(direction) {
                case 'up':
                    cameraY = Math.max(cameraY - moveSpeed, -200);
                    break;
                case 'down':
                    cameraY = Math.min(cameraY + moveSpeed, 200);
                    break;
                case 'left':
                    cameraX = Math.max(cameraX - moveSpeed, -200);
                    break;
                case 'right':
                    cameraX = Math.min(cameraX + moveSpeed, 200);
                    break;
            }

            camera.style.transform = `translate(${cameraX}px, ${cameraY}px)`;
            cameraPosDisplay.textContent = `${cameraX}, ${cameraY}`;
            logEvent(`Camera movement: ${direction}`, 'keyboard');
        }

        // MOUSE HANDLING

        // Mousemove - tracking mouse position
        viewport.addEventListener('mousemove', function(e) {
            const rect = viewport.getBoundingClientRect();
            const x = Math.floor(e.clientX - rect.left);
            const y = Math.floor(e.clientY - rect.top);
            mousePosDisplay.textContent = `${x}, ${y}`;
        });

        // Click - single click
        viewport.addEventListener('click', function(e) {
            clickCount++;
            clickCountDisplay.textContent = clickCount;

            const rect = viewport.getBoundingClientRect();
            const x = Math.floor(e.clientX - rect.left);
            const y = Math.floor(e.clientY - rect.top);

            logEvent(`Click at position: (${x}, ${y})`, 'click');
        });

        // Double click - double click (zoom)
        viewport.addEventListener('dblclick', function(e) {
            const currentScale = camera.style.transform.includes('scale') ? 1 : 1.5;
            const newScale = currentScale === 1 ? 1.5 : 1;

            camera.style.transform = `translate(${cameraX}px, ${cameraY}px) scale(${newScale})`;
            logEvent(`Zoom: ${newScale === 1 ? 'Off' : 'On'}`, 'click');
        });

        // Mouseenter/mouseleave - hovering over the viewport
        viewport.addEventListener('mouseenter', function() {
            viewport.style.borderColor = '#3498db';
            logEvent('Mouse entered camera area', 'mouse');
        });

        viewport.addEventListener('mouseleave', function() {
            viewport.style.borderColor = '#7f8c8d';
            logEvent('Mouse left camera area', 'mouse');
        });

        // Click on dinosaur
        document.querySelectorAll('.dinosaur').forEach(dino => {
            dino.addEventListener('click', function(e) {
                e.stopPropagation(); // Stop propagation to the viewport

                const name = this.dataset.name;
                this.classList.add('clicked');

                setTimeout(() => {
                    this.classList.remove('clicked');
                }, 500);

                logEvent(`Clicked dinosaur: ${name}`, 'click');
                console.log(`Observing: ${name}`);
            });

            dino.addEventListener('mouseenter', function() {
                const name = this.dataset.name;
                logEvent(`Hovered over: ${name}`, 'mouse');
            });
        });

        // KEYBOARD HANDLING

        // Keydown - key press
        document.addEventListener('keydown', function(e) {
            lastKeyDisplay.textContent = e.key;

            switch(e.key) {
                case 'ArrowUp':
                    e.preventDefault();
                    moveCamera('up');
                    break;
                case 'ArrowDown':
                    e.preventDefault();
                    moveCamera('down');
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    moveCamera('left');
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    moveCamera('right');
                    break;
                case ' ':
                    e.preventDefault();
                    isPaused = !isPaused;
                    logEvent(`Pause: ${isPaused ? 'ON' : 'OFF'}`, 'keyboard');
                    viewport.style.opacity = isPaused ? '0.5' : '1';
                    break;
                case 'Escape':
                    logEvent('Escape pressed - closing view', 'keyboard');
                    alert('Camera view will be closed');
                    break;
                case 'r':
                case 'R':
                    // Camera reset
                    cameraX = 0;
                    cameraY = 0;
                    camera.style.transform = 'translate(0px, 0px)';
                    cameraPosDisplay.textContent = '0, 0';
                    logEvent('Camera position reset', 'keyboard');
                    break;
                default:
                    logEvent(`Key pressed: ${e.key}`, 'keyboard');
            }
        });

        // Handle arrow buttons
        document.querySelectorAll('.arrow-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const direction = this.dataset.direction;
                moveCamera(direction);
            });
        });

        // Initialization
        logEvent('Camera system started', 'keyboard');
        console.log('Jurassic Park monitoring system - ONLINE');
        console.log('Use arrows to move the camera');
        console.log('Click on dinosaurs to observe them');
    </script>
</body>
</html>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which keyboard event does the browser send when any key is pressed (including Shift, Ctrl or the arrow keys) and repeat while the key is held down?

  2. 2. Which event is triggered after the page has fully loaded?

Hands-on tasks in the game

  • Code editor

    The index.html file has two paddocks (.enclosure) and dinosaur cards with the draggable="true" attribute. On dragstart each card stores its id in dataTransfer. Fill in the blanks: ___BLANK1___ is the event a paddock receives while a dragged card is over it (preventDefault() there allows the drop), and ___BLANK2___ is the dataTransfer method that reads the stored id in drop. A dropped card should end up in the paddock it was dropped on.

  • Vertical ordering

    Arrange mouse events in the order they occur during a click:

  • Click in order

    Arrange the code for checking the Ctrl+S combination.

  • Vertical ordering

    Arrange touch events in the order they occur:

  1. QuestionQuiz: Keyboard Events
  2. QuestionQuiz: Window Events
  3. Coding taskExercise: Drag and Drop
  4. Put in orderVertical Sort: Mouse Events
  5. Click in orderSort: Key Combinations
  6. Put in orderVertical Sort: Touch Events

Useful articles