5.3 DOM Manipulation and Event Handling

We use modern DOM APIs rather than jQuery for new projects, as browser support for these APIs is now excellent. Event delegation helps us handle events efficiently, particularly for dynamically generated content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Event delegation for dynamic content
document.addEventListener('click', (e) => {
    // Handle modal triggers
    if (e.target.matches('[data-modal-trigger]')) {
        e.preventDefault();
        const modalId = e.target.dataset.modalTrigger;
        openModal(modalId);
    }

    // Handle form submissions
    if (e.target.matches('.ajax-form button[type="submit"]')) {
        e.preventDefault();
        handleFormSubmission(e.target.closest('form'));
    }
});

async function handleFormSubmission(form) {
    const formData = new FormData(form);

    try {
        const response = await fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        const result = await response.json();

        if (result.success) {
            showSuccessMessage(result.message);
            form.reset();
        } else {
            showErrorMessage(result.message);
        }
    } catch (error) {
        showErrorMessage('An error occurred. Please try again.');
    }
}

Copyright © 2025 Crowd Favorite. All rights reserved.

This site uses Just the Docs, a documentation theme for Jekyll.