Bab 6: HTML5 APIs dan Advanced Features

Bab 6: HTML5 APIs dan Advanced Features

6.1 Storage APIs

6.1.1 LocalStorage

// Menyimpan data
localStorage.setItem('username', 'john_doe');
localStorage.setItem('preferences', JSON.stringify({
    theme: 'dark',
    fontSize: '16px'
}));

// Mengambil data
const username = localStorage.getItem('username');
const preferences = JSON.parse(localStorage.getItem('preferences'));

// Menghapus data
localStorage.removeItem('username');

// Menghapus semua data
localStorage.clear();

// Event listener untuk storage changes
window.addEventListener('storage', (e) => {
    console.log('Storage changed:', e.key, e.newValue);
});

6.1.2 SessionStorage

// Menyimpan data sesi
sessionStorage.setItem('cartItems', JSON.stringify([
    { id: 1, name: 'Product 1' },
    { id: 2, name: 'Product 2' }
]));

// Mengambil data sesi
const cartItems = JSON.parse(sessionStorage.getItem('cartItems'));

// Menghapus data sesi
sessionStorage.removeItem('cartItems');

// Menghapus semua data sesi
sessionStorage.clear();

6.1.3 IndexedDB

// Membuka database
const request = indexedDB.open('MyDatabase', 1);

request.onerror = (event) => {
    console.error('Database error:', event.target.error);
};

request.onupgradeneeded = (event) => {
    const db = event.target.result;
    
    // Membuat object store
    const store = db.createObjectStore('customers', {
        keyPath: 'id',
        autoIncrement: true
    });
    
    // Membuat index
    store.createIndex('name', 'name', { unique: false });
    store.createIndex('email', 'email', { unique: true });
};

request.onsuccess = (event) => {
    const db = event.target.result;
    
    // Menambah data
    const transaction = db.transaction(['customers'], 'readwrite');
    const store = transaction.objectStore('customers');
    
    store.add({
        name: 'John Doe',
        email: 'john@example.com'
    });
    
    // Mengambil data
    const getRequest = store.get(1);
    getRequest.onsuccess = () => {
        console.log('Customer:', getRequest.result);
    };
};

6.1.4 Cache API

// Menyimpan response ke cache
caches.open('my-cache').then(cache => {
    cache.add('/styles.css');
    cache.add('/script.js');
    
    // Atau menggunakan addAll
    cache.addAll([
        '/',
        '/styles.css',
        '/script.js',
        '/images/logo.png'
    ]);
});

// Mengambil data dari cache
caches.match('/styles.css')
    .then(response => {
        if (response) {
            return response;
        }
        return fetch('/styles.css');
    });

// Service Worker dengan Cache
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => response || fetch(event.request))
    );
});

6.2 Drag and Drop

6.2.1 Draggable Elements

<!-- Element yang bisa di-drag -->
<div draggable="true" id="dragMe">
    Drag saya!
</div>

<script>
const element = document.getElementById('dragMe');

element.addEventListener('dragstart', (e) => {
    e.dataTransfer.setData('text/plain', e.target.id);
    e.target.classList.add('dragging');
});

element.addEventListener('dragend', (e) => {
    e.target.classList.remove('dragging');
});
</script>

6.2.2 Drop Zones

<div id="dropZone" class="drop-zone">
    Drop di sini!
</div>

<script>
const dropZone = document.getElementById('dropZone');

dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    const id = e.dataTransfer.getData('text/plain');
    const draggableElement = document.getElementById(id);
    dropZone.appendChild(draggableElement);
});
</script>

6.2.3 File Drag and Drop

<div id="fileDropZone" class="file-drop-zone">
    Drop file di sini
</div>

<script>
const fileDropZone = document.getElementById('fileDropZone');

fileDropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    fileDropZone.classList.add('drag-over');
});

fileDropZone.addEventListener('dragleave', () => {
    fileDropZone.classList.remove('drag-over');
});

fileDropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    fileDropZone.classList.remove('drag-over');
    
    const files = Array.from(e.dataTransfer.files);
    handleFiles(files);
});

function handleFiles(files) {
    files.forEach(file => {
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = document.createElement('img');
                img.src = e.target.result;
                fileDropZone.appendChild(img);
            };
            reader.readAsDataURL(file);
        }
    });
}
</script>

6.3 Geolocation dan Device APIs

6.3.1 Geolocation API

// Mengecek dukungan Geolocation
if ('geolocation' in navigator) {
    // Get current position
    navigator.geolocation.getCurrentPosition(
        // Success callback
        (position) => {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
            console.log(`Location: ${latitude}, ${longitude}`);
        },
        // Error callback
        (error) => {
            console.error('Error:', error.message);
        },
        // Options
        {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        }
    );
    
    // Watch position
    const watchId = navigator.geolocation.watchPosition(
        (position) => {
            console.log('Updated location:', position);
        },
        (error) => {
            console.error('Error:', error);
        }
    );
    
    // Stop watching
    navigator.geolocation.clearWatch(watchId);
}

6.3.2 Device Orientation

window.addEventListener('deviceorientation', (event) => {
    // Alpha: rotation around z-axis
    const alpha = event.alpha;
    // Beta: front back motion
    const beta = event.beta;
    // Gamma: left to right
    const gamma = event.gamma;
    
    console.log(`Orientation: α: ${alpha}, β: ${beta}, γ: ${gamma}`);
});

window.addEventListener('devicemotion', (event) => {
    // Acceleration
    const x = event.acceleration.x;
    const y = event.acceleration.y;
    const z = event.acceleration.z;
    
    // Acceleration including gravity
    const gx = event.accelerationIncludingGravity.x;
    const gy = event.accelerationIncludingGravity.y;
    const gz = event.accelerationIncludingGravity.z;
    
    console.log(`Motion: x: ${x}, y: ${y}, z: ${z}`);
});

6.3.3 Battery Status

if ('getBattery' in navigator) {
    navigator.getBattery().then(battery => {
        // Battery level
        console.log('Battery level:', battery.level * 100 + '%');
        
        // Charging status
        console.log('Battery charging:', battery.charging);
        
        // Events
        battery.addEventListener('levelchange', () => {
            console.log('Battery level changed:', battery.level);
        });
        
        battery.addEventListener('chargingchange', () => {
            console.log('Battery charging status:', battery.charging);
        });
    });
}

6.3.4 Media Capture

<!-- Camera capture -->
<input type="file" accept="image/*" capture="user">

<!-- Video capture -->
<input type="file" accept="video/*" capture="environment">

<!-- Using MediaDevices API -->
<video id="videoElement"></video>

<script>
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
            const video = document.getElementById('videoElement');
            video.srcObject = stream;
        })
        .catch(error => {
            console.error('Error accessing camera:', error);
        });
}
</script>

Latihan Praktik

Latihan 1: Todo App dengan LocalStorage

Buat aplikasi todo list yang:

  • Menyimpan tasks di LocalStorage

  • Mendukung CRUD operations

  • Memiliki fitur drag and drop untuk mengatur urutan

  • Menyimpan preferensi pengguna

Latihan 2: File Upload dengan Drag and Drop

Buat sistem upload file yang:

  • Mendukung drag and drop

  • Menampilkan preview untuk gambar

  • Memiliki progress indicator

  • Mendukung multiple files

Latihan 3: Location-based Service

Buat aplikasi yang:

  • Menggunakan Geolocation API

  • Menampilkan lokasi di peta

  • Menghitung jarak ke titik tertentu

  • Memperbarui lokasi secara real-time

Ringkasan Bab

  • Storage APIs menyediakan berbagai opsi penyimpanan data

  • Drag and Drop API memungkinkan interaksi yang intuitif

  • Geolocation dan Device APIs memberikan akses ke fitur perangkat

  • HTML5 APIs memperkaya pengalaman pengguna

Quiz Bab 6

  1. Apa perbedaan antara localStorage dan sessionStorage?

  2. Bagaimana cara implementasi drag and drop untuk file?

  3. Jelaskan penggunaan Geolocation API!

  4. Apa fungsi dari Battery Status API?

  5. Bagaimana cara mengakses kamera menggunakan Media Capture?

Referensi

Last updated