Интерактивные примеры JavaScript

Живые демонстрации возможностей JavaScript с возможностью взаимодействия

🎨 Манипуляции с DOM

Изменение текста и HTML

Исходный текст параграфа

function changeText() {
    document.getElementById('text-demo').textContent = 
        'Текст изменен с помощью JavaScript!';
}

function changeHTML() {
    document.getElementById('text-demo').innerHTML = 
        '<strong>Жирный</strong> и <em>курсивный</em> текст';
}

function resetText() {
    document.getElementById('text-demo').textContent = 
        'Исходный текст параграфа';
}

Изменение стилей элементов

Стилизованный блок

function changeColor() {
    const box = document.getElementById('style-box');
    const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A'];
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    box.style.backgroundColor = randomColor;
}

function changeSize() {
    const box = document.getElementById('style-box');
    box.style.width = '300px';
    box.style.height = '150px';
}

function rotate() {
    const box = document.getElementById('style-box');
    box.style.transform = 'rotate(10deg)';
}

Работа с классами CSS

Элемент с классами

Текущие классы: demo-element
function addClass() {
    const element = document.getElementById('class-demo');
    element.classList.add('highlight', 'bordered');
    updateClassInfo();
}

function removeClass() {
    const element = document.getElementById('class-demo');
    element.classList.remove('highlight');
    updateClassInfo();
}

function toggleClass() {
    const element = document.getElementById('class-demo');
    element.classList.toggle('large');
    updateClassInfo();
}

function updateClassInfo() {
    const element = document.getElementById('class-demo');
    const classes = element.className;
    document.getElementById('class-info').textContent = 
        'Текущие классы: ' + classes;
}

📝 Работа с формами

Обработка ввода пользователя

Результат появится здесь
function processInput() {
    const input = document.getElementById('user-input');
    const result = document.getElementById('input-result');
    
    if (input.value.trim() === '') {
        result.textContent = 'Пожалуйста, введите текст';
        result.style.color = 'red';
    } else {
        result.innerHTML = `
            <strong>Вы ввели:</strong> ${input.value}<br>
            <strong>Длина:</strong> ${input.value.length} символов<br>
            <strong>В верхнем регистре:</strong> ${input.value.toUpperCase()}<br>
            <strong>В нижнем регистре:</strong> ${input.value.toLowerCase()}
        `;
        result.style.color = 'black';
    }
}

Калькулятор

Результат:
function calculate() {
    const num1 = parseFloat(document.getElementById('calc-num1').value);
    const num2 = parseFloat(document.getElementById('calc-num2').value);
    const operation = document.getElementById('calc-operation').value;
    const resultDiv = document.getElementById('calc-result');
    
    if (isNaN(num1) || isNaN(num2)) {
        resultDiv.textContent = 'Ошибка: введите числа';
        return;
    }
    
    let result;
    switch(operation) {
        case '+': result = num1 + num2; break;
        case '-': result = num1 - num2; break;
        case '*': result = num1 * num2; break;
        case '/': 
            if (num2 === 0) {
                resultDiv.textContent = 'Ошибка: деление на ноль';
                return;
            }
            result = num1 / num2; 
            break;
    }
    
    resultDiv.textContent = `Результат: ${num1} ${operation} ${num2} = ${result}`;
}

🎯 События мыши и клавиатуры

События мыши

Наведите мышь на эту область

Координаты: X: -, Y: - | События: 0
let eventCount = 0;
const mouseArea = document.getElementById('mouse-area');
const mouseInfo = document.getElementById('mouse-info');

mouseArea.addEventListener('mousemove', (e) => {
    const rect = mouseArea.getBoundingClientRect();
    const x = Math.round(e.clientX - rect.left);
    const y = Math.round(e.clientY - rect.top);
    mouseInfo.textContent = `Координаты: X: ${x}, Y: ${y} | События: ${++eventCount}`;
});

mouseArea.addEventListener('click', (e) => {
    const circle = document.createElement('div');
    circle.style.cssText = `
        position: absolute;
        width: 20px;
        height: 20px;
        background: red;
        border-radius: 50%;
        left: ${e.offsetX - 10}px;
        top: ${e.offsetY - 10}px;
    `;
    mouseArea.appendChild(circle);
});

События клавиатуры

Последняя клавиша: - | Код: - | Нажато клавиш: 0
let keyPressCount = 0;
const keyInput = document.getElementById('keyboard-input');
const keyInfo = document.getElementById('key-info');

keyInput.addEventListener('keydown', (e) => {
    keyPressCount++;
    keyInfo.textContent = 
        `Последняя клавиша: ${e.key} | Код: ${e.code} | Нажато клавиш: ${keyPressCount}`;
    
    // Специальные клавиши
    if (e.key === 'Enter') {
        alert('Нажат Enter!');
    }
    if (e.key === 'Escape') {
        keyInput.value = '';
        keyPressCount = 0;
    }
});

⏱️ Таймеры и анимации

Секундомер

00:00:00
let stopwatchInterval = null;
let stopwatchTime = 0;

function startStopwatch() {
    if (stopwatchInterval) return;
    
    stopwatchInterval = setInterval(() => {
        stopwatchTime++;
        updateStopwatchDisplay();
    }, 1000);
}

function stopStopwatch() {
    clearInterval(stopwatchInterval);
    stopwatchInterval = null;
}

function resetStopwatch() {
    stopStopwatch();
    stopwatchTime = 0;
    updateStopwatchDisplay();
}

function updateStopwatchDisplay() {
    const hours = Math.floor(stopwatchTime / 3600);
    const minutes = Math.floor((stopwatchTime % 3600) / 60);
    const seconds = stopwatchTime % 60;
    
    document.getElementById('stopwatch').textContent = 
        `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
}

function pad(num) {
    return num.toString().padStart(2, '0');
}

Анимация прогресс-бара

0%
function animateProgress() {
    let progress = 0;
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    
    const interval = setInterval(() => {
        progress += 1;
        progressBar.style.width = progress + '%';
        progressText.textContent = progress + '%';
        
        if (progress >= 100) {
            clearInterval(interval);
            setTimeout(() => {
                progressText.textContent = 'Готово! 🎉';
            }, 300);
        }
    }, 20);
}

function resetProgress() {
    document.getElementById('progress-bar').style.width = '0%';
    document.getElementById('progress-text').textContent = '0%';
}

📚 Работа с массивами и объектами

Список задач (TODO List)

Всего задач: 0 | Выполнено: 0
let todos = [];

function addTodo() {
    const input = document.getElementById('todo-input');
    const text = input.value.trim();
    
    if (text === '') return;
    
    const todo = {
        id: Date.now(),
        text: text,
        completed: false
    };
    
    todos.push(todo);
    input.value = '';
    renderTodos();
}

function toggleTodo(id) {
    const todo = todos.find(t => t.id === id);
    if (todo) {
        todo.completed = !todo.completed;
        renderTodos();
    }
}

function deleteTodo(id) {
    todos = todos.filter(t => t.id !== id);
    renderTodos();
}

function renderTodos() {
    const list = document.getElementById('todo-list');
    list.innerHTML = todos.map(todo => `
        <li style="margin: 5px 0;">
            <input type="checkbox" ${todo.completed ? 'checked' : ''} 
                   onchange="toggleTodo(${todo.id})">
            <span style="${todo.completed ? 'text-decoration: line-through;' : ''}">
                ${todo.text}
            </span>
            <button onclick="deleteTodo(${todo.id})" style="margin-left: 10px;">
                Удалить
            </button>
        </li>
    `).join('');
    
    updateTodoStats();
}

function updateTodoStats() {
    const total = todos.length;
    const completed = todos.filter(t => t.completed).length;
    document.getElementById('todo-stats').textContent = 
        `Всего задач: ${total} | Выполнено: ${completed}`;
}

Фильтрация и сортировка данных

const products = [
    { name: 'Ноутбук', price: 1200 },
    { name: 'Мышь', price: 25 },
    { name: 'Клавиатура', price: 75 },
    { name: 'Монитор', price: 450 },
    { name: 'Наушники', price: 150 }
];

let displayProducts = [...products];

function showAllProducts() {
    displayProducts = [...products];
    renderProducts();
}

function filterExpensive() {
    displayProducts = products.filter(p => p.price > 500);
    renderProducts();
}

function sortByPrice() {
    displayProducts.sort((a, b) => a.price - b.price);
    renderProducts();
}

function sortByName() {
    displayProducts.sort((a, b) => a.name.localeCompare(b.name));
    renderProducts();
}

function renderProducts() {
    const list = document.getElementById('products-list');
    list.innerHTML = displayProducts.map(p => 
        `<div>${p.name} - ${p.price}₽</div>`
    ).join('');
}

// Инициализация
showAllProducts();

🎮 Мини-игры

Игра "Поймай кнопку"

Счет: 0 | Рекорд: 0
let catchScore = 0;
let catchRecord = localStorage.getItem('catchRecord') || 0;

function catchButton() {
    const button = document.getElementById('catch-button');
    const container = button.parentElement;
    
    catchScore++;
    
    // Случайная позиция
    const maxX = container.offsetWidth - button.offsetWidth;
    const maxY = container.offsetHeight - button.offsetHeight - 50;
    const newX = Math.random() * maxX;
    const newY = Math.random() * maxY;
    
    button.style.left = newX + 'px';
    button.style.top = newY + 'px';
    
    // Обновление счета
    if (catchScore > catchRecord) {
        catchRecord = catchScore;
        localStorage.setItem('catchRecord', catchRecord);
    }
    
    document.getElementById('catch-score').textContent = 
        `Счет: ${catchScore} | Рекорд: ${catchRecord}`;
    
    // Усложнение игры
    if (catchScore % 5 === 0) {
        button.style.transition = 'all 0.3s';
    }
}

Игра на память

Нажмите "Начать"
Уровень: 1
let memorySequence = '';
let memoryLevel = 1;

function startMemoryGame() {
    memorySequence = generateSequence(memoryLevel + 2);
    const display = document.getElementById('memory-sequence');
    const input = document.getElementById('memory-input');
    
    display.textContent = memorySequence;
    input.value = '';
    input.disabled = true;
    
    setTimeout(() => {
        display.textContent = '?'.repeat(memorySequence.length);
        input.disabled = false;
        input.focus();
    }, 2000);
}

function generateSequence(length) {
    const chars = '0123456789ABCDEF';
    let sequence = '';
    for (let i = 0; i < length; i++) {
        sequence += chars[Math.floor(Math.random() * chars.length)];
    }
    return sequence;
}

function checkMemoryAnswer() {
    const input = document.getElementById('memory-input');
    const result = document.getElementById('memory-result');
    
    if (input.value.toUpperCase() === memorySequence) {
        memoryLevel++;
        result.textContent = `Правильно! Уровень: ${memoryLevel}`;
        result.style.color = 'green';
        startMemoryGame();
    } else {
        result.textContent = `Неправильно! Было: ${memorySequence}. Уровень: 1`;
        result.style.color = 'red';
        memoryLevel = 1;
    }
}