Lab 08: HTML5 APIs
Overview
Step 1: Intersection Observer
// Basic usage
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target); // stop watching once visible
}
});
});
document.querySelectorAll('.animate-on-scroll').forEach(el => {
observer.observe(el);
});
// With options
const lazyObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // load image
img.removeAttribute('data-src');
lazyObserver.unobserve(img);
}
});
}, {
root: null, // null = viewport
rootMargin: '0px 0px -100px 0px', // trigger 100px before bottom edge
threshold: 0.1 // 10% visible triggers callback
});
// Multiple thresholds
const progressObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
// entry.intersectionRatio: 0.0 to 1.0
entry.target.style.opacity = entry.intersectionRatio;
});
}, {
threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0]
});Step 2: Resize Observer
Step 3: Mutation Observer
Step 4: Web Storage
Step 5: Custom Elements
Step 6: Template & Slot (for Custom Elements)
Step 7: Practical Patterns
Step 8: Capstone — jsdom API Simulation
Summary
API
Constructor
Key Methods
Last updated
