Skip to content

Instantly share code, notes, and snippets.

@estrattonbailey
Created August 19, 2016 13:22
Show Gist options
  • Save estrattonbailey/71965a253b1a2057e45ef3ba37416637 to your computer and use it in GitHub Desktop.
Save estrattonbailey/71965a253b1a2057e45ef3ba37416637 to your computer and use it in GitHub Desktop.
Dropdown Snippet
import delegate from 'delegate'
const checkTouch = (root) => {
let select = root.querySelector('.js-select-outer')
let dropdown = root.querySelector('.js-dropdown')
if (!select) return
if (!window.feature.touch){
dropdown.style.display = 'inline-block'
select.style.display = 'none'
}
}
class Dropdown {
constructor(root){
this.select = root.querySelector('.js-select')
this.drop = root.querySelector('.js-drop')
this.button = root.querySelector('.js-button')
this.buttonLabel = this.button.querySelector('.js-label')
checkTouch(root)
root.style.minWidth = root.offsetWidth+'px'
this.options = Array.prototype.slice.call(this.drop.querySelectorAll('.js-option'))
this.active = false
this.button.onclick = (e) => {
e.preventDefault()
this.toggle()
}
// this.button.onblur = this.close.bind(this)
delegate(this.drop, '.js-option', 'click', (e) => {
let index = parseInt(e.delegateTarget.getAttribute('data-index'))
this.setActiveIndex(index, 10)
this.close()
if (this.state) this.state.index = index
})
}
toggle(){
this.active ? this.close() : this.open()
}
open(){
this.drop.style.display = 'block'
this.active = true
}
close(){
this.drop.style.display = 'none'
this.active = false
}
setActiveIndex(index){
for (let i = 0; i < this.options.length; i++){
this.options[i].classList.remove('is-selected')
}
this.options[index].classList.add('is-selected')
this.setLabel(this.options[index].innerHTML)
this.select.selectedIndex = index
}
setLabel(label){
this.buttonLabel.innerHTML = label
}
setState(state){
this.state = state
this.state.watch('index', (i) => {
this.setActiveIndex(i)
this.close()
})
}
}
export default Dropdown
@estrattonbailey
Copy link
Author

Originally written for a couple instances on gitmanvintage.com, but was replaced with React. This is UNTESTED.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment