Skip to content

Instantly share code, notes, and snippets.

@matthewflannery
Created May 12, 2017 00:14
Show Gist options
  • Save matthewflannery/a6ae7fd032ced3823e62b5996f498d3a to your computer and use it in GitHub Desktop.
Save matthewflannery/a6ae7fd032ced3823e62b5996f498d3a to your computer and use it in GitHub Desktop.
// Get siblings of DOM node
function siblings(selector) {
let element = document.querySelector(selector)
let childElements = Array.from(element.parentNode.children)
return childElements.filter(child => child !== element)
}
// Find closest DOM node
function closest(element, query) {
while (!!element && element !== document) {
if (element.matches(query)) {
return element
}
element = element.parentNode
}
return null
}
// Delegates events
/* Delegate events
Example: delegate('body', 'click', '#btn', event => {
state: on
*/
function delegate(selector, eventName, targetSelector, listener) {
document.querySelector(selector).addEventListener(eventName, event => {
let closestMatch = closest(event.target, targetSelector)
if (closestMatch) {
event.delegateTarget = closestMatch
listener(event)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment