-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquantity-input.js
More file actions
60 lines (47 loc) · 1.5 KB
/
Copy pathquantity-input.js
File metadata and controls
60 lines (47 loc) · 1.5 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
class WudoQuantity extends HTMLElement {
connectedCallback() {
this.input = this.querySelector('input');
this.btnMinus = this.querySelector('[data-action="minus"]');
this.btnPlus = this.querySelector('[data-action="plus"]');
this.step = parseInt(this.dataset.step) || 1;
this.min = parseInt(this.dataset.min) || 0;
this.max = this.dataset.max ? parseInt(this.dataset.max) : Infinity;
this.btnMinus.addEventListener('click', () => this.changeValue(-this.step));
this.btnPlus.addEventListener('click', () => this.changeValue(this.step));
this.input.addEventListener('change', () => this.validate());
this.validate();
}
changeValue(delta) {
let val = parseInt(this.input.value) + delta;
this.input.value = val;
this.validate();
const dataset = { ...this.dataset };
this.dispatchEvent(new CustomEvent('quantity:update', {
detail: {
value: val,
...dataset
},
bubbles: true
}));
this.input.dispatchEvent(new Event('change', { bubbles: true }));
}
validate() {
let val = parseInt(this.input.value);
if (val <= this.min) {
val = this.min;
this.btnMinus.disabled = true;
} else {
this.btnMinus.disabled = false;
}
if (val >= this.max) {
val = this.max;
this.btnPlus.disabled = true;
} else {
this.btnPlus.disabled = false;
}
this.input.value = val;
}
}
if (!customElements.get('wudo-quantity')) {
customElements.define('wudo-quantity', WudoQuantity);
}