Skip to content

Latest commit

 

History

History
81 lines (67 loc) · 2.33 KB

modern-javascript-patterns.md

File metadata and controls

81 lines (67 loc) · 2.33 KB
layout default
title Modern JavaScript Patterns
description We use ES6 classes, arrow functions, destructuring, and template literals where they improve code readability and maintainability...
section JavaScript
section_slug javascript
parent JavaScript
nav_order 1
permalink /javascript/modern-javascript-patterns/

5.1 Modern JavaScript Patterns

We use ES6 classes, arrow functions, destructuring, and template literals where they improve code readability and maintainability. However, we don't use new features just for the sake of using them: each language feature should serve a purpose in making our code clearer or more efficient.

// Component-based JavaScript for both WordPress and Laravel
class ImageGallery {
    constructor(element, options = {}) {
        this.element = element;
        this.options = {
            autoplay: false,
            showThumbnails: true,
            ...options
        };

        this.currentIndex = 0;
        this.images = this.element.querySelectorAll('.gallery-image');

        this.init();
    }

    init() {
        this.bindEvents();
        if (this.options.autoplay) {
            this.startAutoplay();
        }
    }

    bindEvents() {
        const nextBtn = this.element.querySelector('.gallery-next');
        const prevBtn = this.element.querySelector('.gallery-prev');

        nextBtn?.addEventListener('click', () => this.next());
        prevBtn?.addEventListener('click', () => this.previous());

        // Keyboard accessibility
        this.element.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowRight') this.next();
            if (e.key === 'ArrowLeft') this.previous();
        });
    }

    next() {
        this.currentIndex = (this.currentIndex + 1) % this.images.length;
        this.updateDisplay();
    }

    previous() {
        this.currentIndex = this.currentIndex === 0
            ? this.images.length - 1
            : this.currentIndex - 1;
        this.updateDisplay();
    }

    updateDisplay() {
        this.images.forEach((img, index) => {
            img.classList.toggle('active', index === this.currentIndex);
        });
    }
}

// Initialize galleries
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.image-gallery').forEach(gallery => {
        new ImageGallery(gallery);
    });
});