// Menyimpan datalocalStorage.setItem('username','john_doe');localStorage.setItem('preferences',JSON.stringify({ theme:'dark', fontSize:'16px'}));// Mengambil dataconstusername=localStorage.getItem('username');constpreferences=JSON.parse(localStorage.getItem('preferences'));// Menghapus datalocalStorage.removeItem('username');// Menghapus semua datalocalStorage.clear();// Event listener untuk storage changeswindow.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>