Created
May 12, 2017 00:14
-
-
Save matthewflannery/a6ae7fd032ced3823e62b5996f498d3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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