Last active
August 17, 2016 02:11
-
-
Save estrattonbailey/9d5fe7a61229754409e4d3110a56938e to your computer and use it in GitHub Desktop.
Reactive Counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function(el){ | |
const input = el.querySelector('.js-counter-input') | |
const buttons = Array.prototype.slice.call(el.querySelectorAll('button')) | |
const state = { | |
min: parseInt(input.getAttribute('min'),10) || 0, | |
max: parseInt(input.getAttribute('max'),10) || 9999, | |
store: { | |
value: parseInt(input.value,10) | |
}, | |
set value(val){ | |
val = typeof val === 'number' ? val : state.min; | |
this.store.value = val | |
input.value = val | |
}, | |
get value(){ | |
return this.store.value | |
} | |
} | |
function clamp(val){ | |
let _val | |
if (val >= state.min && val <= state.max){ | |
_val = val | |
} else if (val >= state.max){ | |
_val = state.max | |
} else if (val <= state.min){ | |
_val = state.min | |
} | |
return _val; | |
} | |
function updateValue(el){ | |
let type = event.target.getAttribute('data-count') | |
let val = type === '+' ? 1 : -1 | |
state.value = (val === 1) ? | |
Math.min(state.value + val, state.max) : | |
Math.max(state.value + val, state.min) | |
} | |
function checkValue(){ | |
let val = input.value | |
state.value = clamp(val) | |
} | |
for (var i = 0; i < buttons.length; i++){ | |
buttons[i].addEventListener('click', function(e){ | |
e.preventDefault() | |
updateValue(event.target) | |
}); | |
} | |
input.onchange = function(e){ | |
state.value = clamp(parseInt(e.target.value,10)) | |
} | |
checkValue() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment