vanillajs-browser-helpers
Version:
Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser
22 lines (21 loc) • 597 B
JavaScript
import isEventTarget from './isEventTarget';
const customEvent = (name, data) => {
const options = { bubbles: true };
if (typeof data !== 'undefined') {
options.detail = data;
}
return new CustomEvent(name, options);
};
function trigger(elm, eventNames, data) {
if (!isEventTarget(elm)) {
data = eventNames;
eventNames = elm;
elm = document;
}
if (!Array.isArray(eventNames)) {
eventNames = [eventNames];
}
eventNames.forEach((evt) => elm.dispatchEvent(customEvent(evt, data)));
return elm;
}
export default trigger;