-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontohLocal.html
More file actions
65 lines (59 loc) · 1.98 KB
/
contohLocal.html
File metadata and controls
65 lines (59 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<head>
<title>Web Storage World</title>
<style>
.contents {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid black;
padding: 15px;
}
#generateButton {
margin-top: 5px;
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="contents" align="center">
<h2>LOCAL STORAGE</h2>
<button id="incrementButton">Tambah nilai</button>
<button id="clear">Hapus storage</button>
<h3>Kamu sudah menekan tombol di atas sebanyak:</h3>
<h2 id="count">0</h2>
</div>
<script>
const localStorageKey = 'PRESS_FREQUENCY';
// pengecekan apakah data localStorage dengan key count tersedia atau belum
if (typeof (Storage) !== 'undefined') {
if (localStorage.getItem(localStorageKey) === null) {
// Jika item pada local storage belum ada
// maka akan diberi nilai awal yakni 0
localStorage.setItem(localStorageKey, 0);
}
const Incrementbutton = document.querySelector('#incrementButton');
const clearButton = document.querySelector('#clear');
const countDisplay = document.querySelector('#count');
// memberikan nilai item dari local storage
countDisplay.innerText = localStorage.getItem(localStorageKey);
// mengupdate nilai dari item local storage jika tombol ditekan
Incrementbutton.addEventListener('click', function () {
let count = localStorage.getItem(localStorageKey);
count++;
localStorage.setItem(localStorageKey, count);
countDisplay.innerText = localStorage.getItem(localStorageKey);
});
// memberikan nilai 0 ke tampilan karena di-reset dan menghapus item
clearButton.addEventListener('click', function () {
localStorage.removeItem(localStorageKey);
countDisplay.innerText = 0;
});
} else {
alert('Browser yang Anda gunakan tidak mendukung Web Storage');
}
</script>
</body>
</html>