Intersection Observer API HTML

Сложность: Продвинутый

Intersection Observer API в HTML

Эффективное отслеживание появления элементов в viewport.

Пример использования:

<style>
.section {
    height: 500px;
    border: 1px solid #ccc;
    margin: 20px 0;
    padding: 20px;
    opacity: 0.3;
    transition: opacity 0.5s;
}

.section.visible {
    opacity: 1;
    background: #f0f0f0;
}
</style>

<div class="section" id="section1">Секция 1</div>
<div class="section" id="section2">Секция 2</div>
<div class="section" id="section3">Секция 3</div>
<div class="section" id="section4">Секция 4</div>

<script>
// Создание наблюдателя
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add("visible");
            console.log(`${entry.target.id} теперь видима`);
        } else {
            entry.target.classList.remove("visible");
        }
    });
}, {
    threshold: 0.5, // Срабатывает когда 50% элемента видно
    rootMargin: "0px 0px -100px 0px" // Игнорирует нижние 100px
});

// Наблюдение за всеми секциями
document.querySelectorAll(".section").forEach(section => {
    observer.observe(section);
});

// Lazy loading изображений
const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src;
            img.classList.remove("lazy");
            imageObserver.unobserve(img);
        }
    });
});

document.querySelectorAll("img.lazy").forEach(img => {
    imageObserver.observe(img);
});
</script>