Skip to content

Instantly share code, notes, and snippets.

@y-nk
Last active February 6, 2020 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save y-nk/d5b31eaafdf4377760c9df80602adad1 to your computer and use it in GitHub Desktop.
Save y-nk/d5b31eaafdf4377760c9df80602adad1 to your computer and use it in GitHub Desktop.
// import { isTouchEnable } from '../es6/functions.js';
/** Display autocomplete component on searches */
var Autocomplete = function(settings) {
this.settings = {
element: settings.element,
}
this.init();
}
Autocomplete.prototype.init = function init() {
if (!this.settings.element) {
return
}
this.setElements();
this.addEvents();
}
Autocomplete.prototype.destroy = function destroy() {
this.removeEvents();
}
Autocomplete.prototype.setElements = function setElements() {
const listSuggestsSelector = this.settings.element.getAttribute('aria-owns');
this.elements = {
listSuggests: document.querySelector(`#${listSuggestsSelector}`)
}
}
Autocomplete.prototype.addEvents() {
this._listeners = {
onFocusInput: e => this.onFocusInput(e)
onBlurInput: e => this.onBlurInput(e)
onKeypressInput: e => this.onKeypressInput(e)
}
this.settings.element.addEventListener('focus', this._listeners.onFocusInput)
this.settings.element.addEventListener('blur', this._listeners.onBlurInput)
this.settings.element.addEventListener('keydown', this._listeners.onKeypressInput)
}
Autocomplete.prototype.removeEvents() {
this.settings.element.removeEventListener('focus', this._listeners.onFocusInput)
this.settings.element.removeEventListener('blur', this._listeners.onBlurInput)
this.settings.element.removeEventListener('keydown', this._listeners.onKeypressInput)
}
Autocomplete.prototype.onFocusInput = function onFocusInput() {
document.body.setAttribute("data-autocomplete-has-focus", true)
}
Autocomplete.prototype.onBlurInput = function onBlurInput() {
document.body.setAttribute("data-autocomplete-has-focus", false)
}
Autocomplete.prototype.onKeypressInput = function onKeypressInput(event) {
const keyCode = event.keyCode;
switch (keyCode) {
case 40:
event.preventDefault()
const currentSelected = this.elements.listSuggests.querySelector(`[aria-selected="true"]`)
const nextSelected = currentSelected.nextElementSibling
currentSelected.setAttribute("aria-selected", false)
nextSelected.setAttribute("aria-selected", true)
case 38:
event.preventDefault()
break;
default:
}
}
export default Autocomplete;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment