A work-in-progress dropdown module crafted to seamlessly integrate with predominantly vanilla Javascript applications.
Use it with simple text values:
<div class="dropdown-button">
<button>Choose an option</button>
</div>
<div class="dropdown">
<div class="option" data-value="1">
Option 1
</div>
<div class="option" data-value="2">
Option 2
</div>
<div class="option" data-value="3">
Option 3
</div>
</div>
<input type="hidden" class="dropdown-value">
With caret/chevron or any other svg icon:
<div class="dropdown-button">
<button>
Choose an option
<span class="caret">
<!-- Your <svg> here -->
</span>
</button>
</div>
<div class="dropdown">
<div class="option" data-value="1">
Option 1
</div>
<div class="option" data-value="2">
Option 2
</div>
<div class="option" data-value="3">
Option 3
</div>
</div>
<input type="hidden" class="dropdown-value">
Or with span element and text:
<div class="dropdown-button">
<button>Choose an emoji</button>
</div>
<div class="dropdown">
<div class="option" data-value="1">
<span>👾</span> Games
</div>
<div class="option" data-value="2">
<span>🤖</span> Robots
</div>
<div class="option" data-value="3">
<span>🎃</span> Pumpkins
</div>
</div>
<input type="hidden" class="dropdown-value">
Import the module:
const Dropdown = require('@juhojama/dropdown')
new Dropdown({ el: element, useTabIndex: true }).init()
You can monitor changes in dropdown by following ways:
- Listen for the custom event 'dropdownChange'
dropdown.el.addEventListener('dropdownChange', function (event) {
console.log('User chose option with value: ' + event.detail.value)
console.log('Option label: ' + event.detail.label)
})
- Use MutationObserver:
let observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type === 'attributes' && mutation.attributeName === 'value') {
console.log('Input value has changed:', mutation.target.value)
}
})
})
let hiddenInputs = document.querySelectorAll('input[type="hidden"]')
hiddenInputs.forEach(input => {
observer.observe(input, {
attributes: true,
attributeFilter: ['value']
})
})