-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.html
54 lines (45 loc) · 2.26 KB
/
counter.html
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
<!Doctype html>
<html lang="en" class="h-100 d-flex justify-content-center align-items-center">
<head>
<title>Counter</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script>
// If no counter value in the local storage create one
if (!localStorage.getItem('counter')) {
localStorage.setItem('counter', 0);
}
let counter = parseInt(localStorage.getItem('counter'));
// Wait for content to be loaded
document.addEventListener("DOMContentLoaded", function() {
// Get the the counter value from local storage
document.querySelector('#counter').innerHTML = counter;
// Have each button change the value of the counter
document.querySelectorAll('.counter').forEach(function(button) {
button.onclick = function() {
let n = parseInt(button.dataset.val)
if (n != 0) {
counter += n;
} else {
counter = n;
};
// Update the counter value
localStorage.setItem('counter', counter);
document.querySelector('#counter').innerHTML = counter;
};
});
});
</script>
</head>
<body class="d-flex flex-column align-items-center">
<h1 class="display-4">Counter</h1>
<h2 class="display-1" id="counter">0</h2>
<div class="d-flex mt-4">
<button class="counter btn btn-success shadow-sm mr-2" data-val="1">Add</button>
<button class="counter btn btn-warning shadow-sm mr-2" data-val="-1">Sub</button>
<button class="counter btn btn-danger shadow-sm" data-val="0">Reset</button>
</div>
<a class="small text-muted mt-4" href="index.html">Back to index</a>
</body>
</html>