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

The Event Object and Its Properties

9 min read ยท
In this lesson8

"Every sensor report in the park," Ray Arnold opens the detailed system documentation, "contains precise information: where, when, what type of event, with what intensity. Similarly, the Event object in JavaScript is a complete report about what happened in the browser."

Ray points to a monitor showing data from a motion sensor near the T-Rex enclosure. "See? Time: 14:23:47, location: sector B-7, movement type: fast, direction: north. Every piece of information is crucial for the proper response."

What Is the Event Object?

Every event in JavaScript automatically creates an Event object, which is passed to the handler function as its first parameter. This object contains all relevant information about the event - from cursor position, through pressed keys, to the element that triggered the event.

Basic Anatomy of the Event Object

"Let's start with the fundamentals," says Ray, opening the diagnostic panel.

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

parkMap.addEventListener('click', function(event) {
  // event is an object containing all the information

  console.log('=== EVENT REPORT ===');
  console.log('Event type:', event.type); // 'click'
  console.log('Timestamp:', event.timeStamp); // time in ms since page load
  console.log('Event phase:', event.eventPhase); // 1=capture, 2=target, 3=bubble

  // Click position information
  console.log(`Clicked at position: X=${event.clientX}, Y=${event.clientY}`);

  // The element that was clicked
  console.log('Clicked element:', event.target);
  console.log('Tag name:', event.target.tagName);
  console.log('Element ID:', event.target.id);

  // The element the event listener is attached to
  console.log('Element with listener:', event.currentTarget);

  // Can the default action be canceled?
  console.log('Cancelable:', event.cancelable);

  // Does the event bubble?
  console.log('Bubbles:', event.bubbles);
});

Position Properties - Coordinate Systems

"In Jurassic Park," Ray explains, "we use different coordinate systems - GPS, local sector coordinates, positions relative to gates. Similarly, JavaScript offers several coordinate systems for mouse position."

Different Types of Coordinates

const viewingPlatform = document.getElementById('platform');

viewingPlatform.addEventListener('click', function(event) {
  console.log('=== COORDINATE SYSTEMS ===');

  // 1. clientX/Y - position relative to the browser window (viewport)
  console.log('Viewport:', event.clientX, event.clientY);
  console.log('Like position relative to your control monitor');

  // 2. pageX/Y - position relative to the entire page (accounts for scroll)
  console.log('Page:', event.pageX, event.pageY);
  console.log('Like coordinates on the full park map');

  // 3. screenX/Y - position relative to the entire screen
  console.log('Screen:', event.screenX, event.screenY);
  console.log('Like GPS position - absolute location');

  // 4. offsetX/Y - position relative to the clicked element
  console.log('Offset:', event.offsetX, event.offsetY);
  console.log('Like position within a specific enclosure');

  // Practical use - marking area on the map
  markLocationOnMap(event.pageX, event.pageY);
  showCoordinatesInfo(event.clientX, event.clientY);
});

function markLocationOnMap(x, y) {
  const marker = document.createElement('div');
  marker.className = 'location-marker';
  marker.style.left = x + 'px';
  marker.style.top = y + 'px';
  document.body.appendChild(marker);

  console.log(`Location marked on map: (${x}, ${y})`);
}

function showCoordinatesInfo(clientX, clientY) {
  const tooltip = document.getElementById('coordinates-tooltip');
  tooltip.textContent = `Position: X=${clientX}, Y=${clientY}`;
  tooltip.style.left = (clientX + 10) + 'px';
  tooltip.style.top = (clientY + 10) + 'px';
  tooltip.style.display = 'block';
}

target vs currentTarget - The Key Difference

"This is one of the most common mistakes," Ray warns. "Confusing target with currentTarget. It's like confusing the dinosaur that escaped with the enclosure it escaped from."

Understanding the Difference

// HTML:
// <div id="enclosure" class="dino-enclosure">
//   <div class="info-panel">
//     <h3>T-Rex Enclosure</h3>
//     <button class="feed-button">Feed</button>
//     <button class="status-button">Status</button>
//   </div>
// </div>

const enclosure = document.getElementById('enclosure');

enclosure.addEventListener('click', function(event) {
  // target - the element that was ACTUALLY clicked
  console.log('Target (clicked element):', event.target);
  console.log('Target tag:', event.target.tagName);

  // currentTarget - the element the listener is attached to
  console.log('CurrentTarget (element with listener):', event.currentTarget);
  console.log('CurrentTarget ID:', event.currentTarget.id); // always 'enclosure'

  // Practical example
  if (event.target.classList.contains('feed-button')) {
    console.log('Feed button clicked');
    console.log('In enclosure:', event.currentTarget.id);
    feedDinosaur(event.currentTarget.id);
  } else if (event.target.classList.contains('status-button')) {
    console.log('Status button clicked');
    console.log('For enclosure:', event.currentTarget.id);
    showEnclosureStatus(event.currentTarget.id);
  } else {
    console.log('Clicked somewhere in the enclosure, but not on a button');
  }
});

function feedDinosaur(enclosureId) {
  console.log(`Starting feeding in enclosure: ${enclosureId}`);
  console.log('Activating security system...');
  console.log('Dispensing food...');
  console.log('Feeding completed');
}

function showEnclosureStatus(enclosureId) {
  console.log(`=== ENCLOSURE STATUS ${enclosureId} ===`);
  console.log('Temperature: 28ยฐC');
  console.log('Humidity: 65%');
  console.log('Last feeding: 12:30');
  console.log('Dinosaur activity: Normal');
}

Modifier Keys - Multi-Function Actions

"In critical systems," Ray explains, "we often need key combinations for security. Like two keys for the armory. The Event object shows us which keys are pressed."

Detecting Modifier Keys

const dinosaurCard = document.querySelectorAll('.dinosaur-card');

dinosaurCard.forEach(card => {
  card.addEventListener('click', function(event) {
    console.log('=== KEY ANALYSIS ===');
    console.log('Ctrl pressed:', event.ctrlKey);
    console.log('Shift pressed:', event.shiftKey);
    console.log('Alt pressed:', event.altKey);
    console.log('Meta (Cmd/Win) pressed:', event.metaKey);

    const dinoId = this.dataset.dinoId;
    const dinoName = this.dataset.dinoName;

    // Different actions depending on key combinations
    if (event.ctrlKey && event.shiftKey) {
      // Ctrl + Shift + Click = Advanced options
      console.log('Opening advanced options for:', dinoName);
      openAdvancedOptions(dinoId);

    } else if (event.ctrlKey) {
      // Ctrl + Click = Add to multiple selection
      console.log('Adding to selection:', dinoName);
      addToSelection(dinoId);
      this.classList.toggle('selected');

    } else if (event.shiftKey) {
      // Shift + Click = Select range
      console.log('Range selection to:', dinoName);
      selectRange(dinoId);

    } else if (event.altKey) {
      // Alt + Click = Quick preview
      console.log('Quick preview:', dinoName);
      showQuickPreview(dinoId);

    } else {
      // Normal click
      console.log('Selected:', dinoName);
      clearSelection();
      selectSingle(dinoId);
      this.classList.add('selected');
    }
  });
});

// Helper function implementations
let selectedDinosaurs = [];

function addToSelection(dinoId) {
  if (!selectedDinosaurs.includes(dinoId)) {
    selectedDinosaurs.push(dinoId);
  } else {
    selectedDinosaurs = selectedDinosaurs.filter(id => id !== dinoId);
  }
  console.log('Selected dinosaurs:', selectedDinosaurs);
}

function clearSelection() {
  selectedDinosaurs = [];
  document.querySelectorAll('.dinosaur-card.selected').forEach(card => {
    card.classList.remove('selected');
  });
  console.log('Selection cleared');
}

function selectSingle(dinoId) {
  selectedDinosaurs = [dinoId];
  console.log('Single selection:', dinoId);
}

function selectRange(endId) {
  console.log('Implementing range selection to:', endId);
  // Range selection logic between last selected and current
}

Mouse Button Information

"Different sensors react to different types of signals," Ray shows a panel with three buttons. "Similarly, we can react differently to the left, right, and middle mouse buttons."

Detecting the Mouse Button

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

interactiveMap.addEventListener('mousedown', function(event) {
  console.log('=== MOUSE BUTTON INFORMATION ===');
  console.log('Button:', event.button);
  console.log('0 = left, 1 = middle, 2 = right');
  console.log('Buttons (bitmask):', event.buttons);

  const clickX = event.clientX;
  const clickY = event.clientY;

  switch(event.button) {
    case 0:
      // Left button - standard action
      console.log('Left button: Selecting location');
      selectLocation(clickX, clickY);
      break;

    case 1:
      // Middle button - new tab/window
      console.log('Middle button: Opening in new window');
      event.preventDefault();
      openInNewWindow(clickX, clickY);
      break;

    case 2:
      // Right button - context menu
      console.log('Right button: Context menu');
      showContextMenu(clickX, clickY);
      break;

    default:
      console.log('Unknown button:', event.button);
  }
});

// Blocking the default context menu
interactiveMap.addEventListener('contextmenu', function(event) {
  event.preventDefault();
  console.log('Default menu blocked - using custom menu');
});

function selectLocation(x, y) {
  console.log(`Location selected: (${x}, ${y})`);
  highlightArea(x, y);
}

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

  console.log('Context menu displayed at position:', x, y);
}

Event Object Methods

"Besides properties," Ray shows the next screen, "the Event object also has methods - tools for controlling event behavior."

preventDefault() - Blocking the Default Action

// Example 1: Custom form validation
const securityForm = document.getElementById('security-access-form');

securityForm.addEventListener('submit', function(event) {
  event.preventDefault(); // BLOCK default form submission

  console.log('Form submission intercepted');

  const formData = new FormData(securityForm);
  const accessCode = formData.get('access-code');
  const securityLevel = formData.get('security-level');

  // Custom validation
  if (validateAccessCode(accessCode)) {
    console.log('Access code correct');
    grantAccess(securityLevel);
  } else {
    console.error('Invalid access code!');
    showError('The access code is invalid');
  }
});

// Example 2: Custom navigation
const navigationLinks = document.querySelectorAll('a.custom-navigation');

navigationLinks.forEach(link => {
  link.addEventListener('click', function(event) {
    event.preventDefault(); // BLOCK standard navigation

    const targetUrl = this.getAttribute('href');
    console.log('Link click intercepted:', targetUrl);

    // Custom navigation logic (e.g., SPA routing)
    navigateToPage(targetUrl);
  });
});

function validateAccessCode(code) {
  const validCodes = ['ALPHA-7', 'BETA-4', 'GAMMA-9'];
  return validCodes.includes(code);
}

function navigateToPage(url) {
  console.log('Navigating to:', url);
  // SPA routing implementation
  history.pushState({}, '', url);
  loadPageContent(url);
}

stopPropagation() - Stopping Propagation

// HTML:
// <div class="park-section" id="section-a">
//   <div class="enclosure" id="enclosure-1">
//     <button class="action-button">Action</button>
//   </div>
// </div>

const parkSection = document.getElementById('section-a');
const enclosure = document.getElementById('enclosure-1');
const actionButton = document.querySelector('.action-button');

// Listener on the park section
parkSection.addEventListener('click', function(event) {
  console.log('3. Park section clicked');
  updateSectionStatus();
});

// Listener on the enclosure
enclosure.addEventListener('click', function(event) {
  console.log('2. Enclosure clicked');
  event.stopPropagation(); // STOP! Don't propagate higher
  highlightEnclosure();
});

// Listener on the button
actionButton.addEventListener('click', function(event) {
  console.log('1. Action button clicked');
  performAction();
  // The event will propagate to enclosure, but will be stopped there
});

// Without stopPropagation() in enclosure - we'd see all 3 logs
// With stopPropagation() - we'll only see 1 and 2

stopImmediatePropagation() - Complete Stop

const emergencyButton = document.getElementById('emergency');

// First listener
emergencyButton.addEventListener('click', function(event) {
  console.log('1. First listener - alarm activation');
  activateAlarm();

  event.stopImmediatePropagation(); // STOP EVERYTHING!
});

// Second listener - WON'T execute!
emergencyButton.addEventListener('click', function(event) {
  console.log('2. This listener WON\'T execute');
  closeGates();
});

// Third listener - WON'T execute!
emergencyButton.addEventListener('click', function(event) {
  console.log('3. This one WON\'T execute either');
  notifyStaff();
});

// After clicking, we'll only see the first log

Practical Monitoring System

"Let's combine everything into a working system," says Ray, opening the main code.

class DinosaurMonitoringSystem {
  constructor() {
    this.selectedDinosaurs = [];
    this.monitoringActive = false;
    this.initialize();
  }

  initialize() {
    console.log('Initializing dinosaur monitoring system');
    this.setupEventListeners();
  }

  setupEventListeners() {
    const dinosaurCards = document.querySelectorAll('.dinosaur-card');

    dinosaurCards.forEach(card => {
      // Click event with full analysis
      card.addEventListener('click', (event) => {
        this.handleDinosaurClick(event);
      });

      // Context menu
      card.addEventListener('contextmenu', (event) => {
        event.preventDefault();
        this.showDinosaurMenu(event);
      });

      // Hover effects
      card.addEventListener('mouseenter', (event) => {
        this.showQuickInfo(event);
      });

      card.addEventListener('mouseleave', (event) => {
        this.hideQuickInfo(event);
      });
    });
  }

  handleDinosaurClick(event) {
    const card = event.currentTarget;
    const dinoId = card.dataset.dinoId;
    const dinoName = card.dataset.dinoName;

    console.log('=== CLICK REPORT ===');
    console.log('Dinosaur:', dinoName);
    console.log('Click position:', event.clientX, event.clientY);
    console.log('Timestamp:', event.timeStamp);
    console.log('Ctrl:', event.ctrlKey);
    console.log('Shift:', event.shiftKey);
    console.log('Alt:', event.altKey);
    console.log('Mouse button:', event.button);

    // Selection logic
    if (event.ctrlKey) {
      this.toggleSelection(dinoId, card);
    } else if (event.shiftKey) {
      this.selectRange(dinoId);
    } else {
      this.selectSingle(dinoId, card);
    }
  }

  toggleSelection(dinoId, card) {
    const index = this.selectedDinosaurs.indexOf(dinoId);

    if (index === -1) {
      this.selectedDinosaurs.push(dinoId);
      card.classList.add('selected');
      console.log(`Added ${dinoId} to selection`);
    } else {
      this.selectedDinosaurs.splice(index, 1);
      card.classList.remove('selected');
      console.log(`Removed ${dinoId} from selection`);
    }

    console.log('Selected dinosaurs:', this.selectedDinosaurs);
  }

  selectSingle(dinoId, card) {
    // Clear previous selection
    document.querySelectorAll('.dinosaur-card.selected').forEach(c => {
      c.classList.remove('selected');
    });

    this.selectedDinosaurs = [dinoId];
    card.classList.add('selected');

    console.log('Selected single dinosaur:', dinoId);
  }

  showDinosaurMenu(event) {
    const card = event.currentTarget;
    const dinoId = card.dataset.dinoId;

    console.log('Displaying context menu for:', dinoId);
    console.log('Position:', event.clientX, event.clientY);

    // Menu display logic would go here
  }

  showQuickInfo(event) {
    const card = event.currentTarget;
    const dinoName = card.dataset.dinoName;

    console.log(`Hovered over: ${dinoName}`);
    console.log('Mouse position:', event.clientX, event.clientY);
  }

  hideQuickInfo(event) {
    console.log('Left dinosaur card');
  }
}

// System initialization
const monitoringSystem = new DinosaurMonitoringSystem();

Summary

"The Event object," Ray summarizes, "is your window into the world of user interaction. Every property, every method has its meaning and use. Just as every sensor reading in Jurassic Park helps us maintain safety, Event properties help you create precise, responsive applications."

Key properties:

  • event.target - the element that triggered the event
  • event.currentTarget - the element with the listener
  • event.type - the event type
  • event.clientX/Y, event.pageX/Y - cursor positions
  • event.ctrlKey, event.shiftKey, event.altKey - modifier keys
  • event.button - mouse button

Key methods:

  • event.preventDefault() - block the default action
  • event.stopPropagation() - stop propagation
  • event.stopImmediatePropagation() - stop all listeners
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>Visitor Registration - Jurassic Park</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;
        }

        .registration-container {
            max-width: 500px;
            margin: 0 auto;
            background: rgba(0, 0, 0, 0.8);
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #ecf0f1;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: #bdc3c7;
            font-weight: 500;
        }

        input[type="text"],
        input[type="email"],
        input[type="number"],
        input[type="date"],
        select {
            width: 100%;
            padding: 12px;
            border: 2px solid #34495e;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 16px;
            transition: all 0.3s ease;
            box-sizing: border-box;
        }

        input[type="text"]:focus,
        input[type="email"]:focus,
        input[type="number"]:focus,
        input[type="date"]:focus,
        select:focus {
            outline: none;
            border-color: #3498db;
            background: rgba(255, 255, 255, 0.15);
        }

        .input-valid {
            border-color: #27ae60 !important;
            background: rgba(39, 174, 96, 0.1) !important;
        }

        .input-invalid {
            border-color: #e74c3c !important;
            background: rgba(231, 76, 60, 0.1) !important;
        }

        .error-message {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(45deg, #27ae60, #2ecc71);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(39, 174, 96, 0.3);
        }

        .submit-btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .success-message {
            background: #27ae60;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
            display: none;
        }

        .form-info {
            background: rgba(52, 152, 219, 0.2);
            border: 1px solid #3498db;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .required {
            color: #e74c3c;
        }
    </style>
</head>
<body>
    <div class="registration-container">
        <h1>Visitor Registration</h1>

        <div class="form-info">
            Fill out the form to register for a Jurassic Park tour.
            Fields marked with <span class="required">*</span> are required.
        </div>

        <form id="visitor-form">
            <div class="form-group">
                <label for="name">Full name <span class="required">*</span></label>
                <input type="text" id="name" name="name" required>
                <div class="error-message" id="name-error">Full name must have at least 2 characters</div>
            </div>

            <div class="form-group">
                <label for="email">Email address <span class="required">*</span></label>
                <input type="email" id="email" name="email" required>
                <div class="error-message" id="email-error">Enter a valid email address</div>
            </div>

            <div class="form-group">
                <label for="age">Age <span class="required">*</span></label>
                <input type="number" id="age" name="age" min="5" max="120" required>
                <div class="error-message" id="age-error">Age must be between 5 and 120 years</div>
            </div>

            <div class="form-group">
                <label for="phone">Phone number</label>
                <input type="text" id="phone" name="phone" placeholder="+48 123 456 789">
                <div class="error-message" id="phone-error">Enter a valid phone number</div>
            </div>

            <div class="form-group">
                <label for="visit-date">Visit date <span class="required">*</span></label>
                <input type="date" id="visit-date" name="visit-date" required>
                <div class="error-message" id="date-error">Visit date must be in the future</div>
            </div>

            <div class="form-group">
                <label for="tour-type">Tour type <span class="required">*</span></label>
                <select id="tour-type" name="tour-type" required>
                    <option value="">Choose a tour type</option>
                    <option value="standard">Standard (2h)</option>
                    <option value="vip">VIP with a guide (4h)</option>
                    <option value="night">Night tour (3h)</option>
                    <option value="research">Research tour (6h)</option>
                </select>
                <div class="error-message" id="tour-error">Choose a tour type</div>
            </div>

            <button type="submit" id="submit-btn" class="submit-btn" disabled>
                Register for the tour
            </button>
        </form>

        <div id="success-message" class="success-message">
            Registration completed successfully! Confirmation has been sent to the provided email address.
        </div>
    </div>

    <script>
        // Get references to the form elements
        const form = document.getElementById('visitor-form');
        const submitBtn = document.getElementById('submit-btn');
        const successMessage = document.getElementById('success-message');

        // Validation functions
        function validateName(name) {
            return name.length >= 2;
        }

        function validateEmail(email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }

        function validateAge(age) {
            const ageNum = parseInt(age);
            return ageNum >= 5 && ageNum <= 120;
        }

        function validatePhone(phone) {
            if (phone === '') return true; // Optional field
            const phoneRegex = /^(\+\d{1,3}\s?)?\d{3}\s?\d{3}\s?\d{3}$/;
            return phoneRegex.test(phone.replace(/\s/g, ''));
        }

        function validateDate(date) {
            const selectedDate = new Date(date);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            return selectedDate > today;
        }

        function validateTourType(tourType) {
            return tourType !== '';
        }

        // Function to show/hide errors
        function showError(fieldId, show) {
            const errorElement = document.getElementById(fieldId + '-error');
            const inputElement = document.getElementById({ date: 'visit-date', tour: 'tour-type' }[fieldId] || fieldId);

            if (show) {
                errorElement.style.display = 'block';
                inputElement.classList.add('input-invalid');
                inputElement.classList.remove('input-valid');
            } else {
                errorElement.style.display = 'none';
                inputElement.classList.remove('input-invalid');
                inputElement.classList.add('input-valid');
            }
        }

        // Function checking if form is valid
        function checkFormValidity() {
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const age = document.getElementById('age').value;
            const phone = document.getElementById('phone').value;
            const visitDate = document.getElementById('visit-date').value;
            const tourType = document.getElementById('tour-type').value;

            const isValid = validateName(name) &&
                           validateEmail(email) &&
                           validateAge(age) &&
                           validatePhone(phone) &&
                           validateDate(visitDate) &&
                           validateTourType(tourType);

            submitBtn.disabled = !isValid;
            return isValid;
        }

        // Event listeners for real-time validation
        document.getElementById('name').addEventListener('input', function(e) {
            const isValid = validateName(e.target.value);
            showError('name', !isValid);
            checkFormValidity();
        });

        document.getElementById('email').addEventListener('input', function(e) {
            const isValid = validateEmail(e.target.value);
            showError('email', !isValid);
            checkFormValidity();
        });

        document.getElementById('age').addEventListener('input', function(e) {
            const isValid = validateAge(e.target.value);
            showError('age', !isValid);
            checkFormValidity();
        });

        document.getElementById('phone').addEventListener('input', function(e) {
            const isValid = validatePhone(e.target.value);
            showError('phone', !isValid);
            checkFormValidity();
        });

        document.getElementById('visit-date').addEventListener('input', function(e) {
            const isValid = validateDate(e.target.value);
            showError('date', !isValid);
            checkFormValidity();
        });

        document.getElementById('tour-type').addEventListener('change', function(e) {
            const isValid = validateTourType(e.target.value);
            showError('tour', !isValid);
            checkFormValidity();
        });

        // Handle form submission
        form.addEventListener('submit', function(e) {
            e.preventDefault(); // Prevent default form submission

            // Check validity once more
            if (!checkFormValidity()) {
                alert('Form contains errors. Fix them before submitting.');
                return;
            }

            // Collecting the form data
            const formData = new FormData(form);
            const visitorData = {
                name: formData.get('name'),
                email: formData.get('email'),
                age: parseInt(formData.get('age')),
                phone: formData.get('phone') || 'Not provided',
                visitDate: formData.get('visit-date'),
                tourType: formData.get('tour-type')
            };

            console.log('Visitor data:', visitorData);

            // Simulate sending data
            submitBtn.textContent = 'Registering...';
            submitBtn.disabled = true;

            setTimeout(() => {
                // Hiding the form and showing the success message
                form.style.display = 'none';
                successMessage.style.display = 'block';

                console.log('Registration completed successfully!');

                // After 3 seconds we show the form again
                setTimeout(() => {
                    form.style.display = 'block';
                    successMessage.style.display = 'none';
                    form.reset();
                    submitBtn.textContent = 'Register for the tour';
                    checkFormValidity();

                    // Reset field styles
                    document.querySelectorAll('input, select').forEach(input => {
                        input.classList.remove('input-valid', 'input-invalid');
                    });

                    document.querySelectorAll('.error-message').forEach(error => {
                        error.style.display = 'none';
                    });
                }, 3000);
            }, 2000);
        });

        // Set minimum date to tomorrow
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        document.getElementById('visit-date').min = tomorrow.toISOString().split('T')[0];
    </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 property of the event object contains the element that triggered the event?

  2. 2. What is the event.preventDefault() method used for?

Hands-on tasks in the game

  • Code editor

    The index.html file has a visitor registration form (fields name and email) and a script in a <script> tag. Fill in the blanks: ___BLANK1___ is the form submission event, ___BLANK2___ is the event method that stops the default submission and page reload, and ___BLANK3___ is a condition that is true when the e-mail does not contain an @ sign. Valid data should show a greeting with the name, invalid data an error message.

  • Horizontal ordering

    Arrange the elements for preventing the default action in an event handler:

  1. QuestionQuiz: The Event Object
  2. QuestionQuiz: preventDefault()
  3. Coding taskExercise: Form Handling
  4. Put in orderevent.preventDefault() Syntax

Useful articles