Skip to content

Instantly share code, notes, and snippets.

@petertenhoor
Created July 20, 2019 15:32
Show Gist options
  • Save petertenhoor/40e48f7fb9db4ba9f13d12753e65f271 to your computer and use it in GitHub Desktop.
Save petertenhoor/40e48f7fb9db4ba9f13d12753e65f271 to your computer and use it in GitHub Desktop.
Simple quantity input JS class
class QuantityInput {
/**
* QuantityInput constructor
*
* @param $inputElement
* @param $plusElement
* @param $minusElement
*/
constructor($inputElement = null, $plusElement = null, $minusElement = null) {
//validations
if ($inputElement === null || !$inputElement instanceof HTMLInputElement) throw new Error('Missing required parameter `$inputElement` in class QuantityInput or given parameter was not an input element')
if ($plusElement === null || !$plusElement instanceof Element) throw new Error('Missing required parameter `$plusElement` in class QuantityInput or given parameter was not a valid element')
if ($minusElement === null || !$minusElement instanceof Element) throw new Error('Missing required parameter `$minusElement` in class QuantityInput or given parameter was not a valid element')
//create initial state
this.state = {
$inputElement: $inputElement,
$plusElement: $plusElement,
$minusElement: $minusElement,
value: parseInt($inputElement.value),
step: parseInt($inputElement.getAttribute("step")) || 1,
min: parseInt($inputElement.getAttribute("min")) || 1
}
//bind events
this.state.$plusElement.addEventListener("click", this.handlePlusClick.bind(this))
this.state.$minusElement.addEventListener("click", this.handleMinusClick.bind(this))
}
/**
* Handle plus click
* @param event
*/
handlePlusClick(event) {
if (event) event.preventDefault()
this.updateValue(this.state.value + this.state.step)
}
/**
* Handle minus click
* @param event
*/
handleMinusClick(event) {
if (event) event.preventDefault()
const newValue = this.state.value - this.state.step
if (newValue >= this.state.min) this.updateValue(newValue)
}
/**
* Update value in state and input
* @param newValue
*/
updateValue(newValue) {
this.state.value = newValue
this.state.$inputElement.value = newValue
}
}
export default QuantityInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment