Choices/assets/scripts/src/components/input.js

89 lines
2 KiB
JavaScript
Raw Normal View History

2017-08-21 17:59:56 +02:00
import { getWidthOfInput } from '../lib/utils';
2017-08-17 14:50:14 +02:00
/**
2017-08-21 17:59:56 +02:00
* Input
2017-08-17 14:50:14 +02:00
*/
export default class Input {
constructor(instance, element, classNames) {
this.instance = instance;
this.element = element;
this.classNames = classNames;
// Bind event listeners
this.onPaste = this.onPaste.bind(this);
this.onInput = this.onInput.bind(this);
}
addEventListeners() {
this.element.addEventListener('input', this.onInput);
this.element.addEventListener('paste', this.onPaste);
}
removeEventListeners() {
this.element.removeEventListener('input', this.onInput);
this.element.removeEventListener('paste', this.onPaste);
}
/**
* Input event
* @return
* @private
*/
onInput() {
if (!this.instance.isSelectOneElement) {
this.setWidth();
}
}
/**
* Paste event
* @param {Object} e Event
* @return
* @private
*/
onPaste(e) {
// Disable pasting into the input if option has been set
if (e.target === this.element && !this.instance.config.paste) {
e.preventDefault();
}
2017-08-17 14:50:14 +02:00
}
2017-08-21 09:53:19 +02:00
/**
* Set value of input to blank
* @return {Object} Class instance
* @public
*/
clear(setWidth = true) {
if (this.element.value) {
this.element.value = '';
}
if (setWidth) {
2017-08-21 17:59:56 +02:00
this.setWidth();
2017-08-21 09:53:19 +02:00
}
return this.instance;
}
2017-08-21 17:59:56 +02:00
/**
* Set the correct input width based on placeholder
* value or input value
* @return
*/
setWidth() {
if (this.instance.placeholder) {
// If there is a placeholder, we only want to set the width of the input when it is a greater
// length than 75% of the placeholder. This stops the input jumping around.
if (
this.element.value &&
this.element.value.length >= (this.instance.placeholder.length / 1.25)
) {
this.element.style.width = getWidthOfInput(this.element);
}
} else {
// If there is no placeholder, resize input to contents
this.element.style.width = getWidthOfInput(this.element);
}
}
2017-08-17 14:50:14 +02:00
}