A library of ES6 utilities.
-
Install with
$ yarn add @oddcamp/js-utils
. -
Import utils you need to your project, e.g.:
import { addEventListener } from "js-utils/src/event";
-
Browse Documentation
In order to gain a wider browser support, install and import these polyfills in your project:
- Install dependencies with
$ yarn
- Run
$ yarn dev
when developing. This will:- Run the linter for your own good
- Start server for demos
- Edit contents of
src
and make sure the corresponding examples ondemo
are updated/added
onCssAnimationEnd(elements, callback [, options = { continuous = false, oncePerElems = true, oncePerAnims = true }])
Fires a callback function when CSS animation ends.
Examples:
onCssAnimationEnd(btn, callbackFunction)
onCssAnimationEnd(btns, callbackFunction, {oncePerAnims = false})
onCssAnimationEnd('.btn', callbackFunction)
onCssTransitionEnd(elements, callback [, options = { continuous = false, oncePerElems = true, oncePerAnims = true }])
Fires a callback function when CSS transition ends
Examples:
onCssTransitionEnd(btn, callbackFunction)
onCssTransitionEnd(btns, callbackFunction, {oncePerElems = false})
onCssTransitionEnd('.btn', callbackFunction)
Cleans all CSS animation end event listeners
Cleans all CSS transition end event listeners
An extended implementation of Element.classList.add(): adds classname(s) to single or multiple elements
Examples:
addClass(btn, "btn--green");
addClass(".btn", "btn--disabled btn--grey");
An extended implementation of Element.classList.remove(): removes classname(s) from single or multiple elements
Examples:
removeClass(btn, "btn--green");
removeClass(".btn", "btn--disabled btn--grey");
An extended implementation of Element.classList.remove(): toggles classname(s) from single or multiple elements
Examples:
toggleClass(btn, "btn--green", true);
toggleClass(".btn", "btn--disabled btn--grey");
Check if an element contains at least one classname
Examples:
containsAnyClass(btn, "btn--green btn--disabled btn--grey");
containsAnyClass(".btn", "btn--green btn--disabled btn--grey");
Check if an element contains all classnames
Examples:
containsAllClasses(btn, "btn--green btn--disabled btn--grey");
containsAllClasses(".btn", "btn--green btn--disabled btn--grey");
Finds cookie by name and returns its value.
Examples:
getCookieValue("_ga");
Attaches the event handler. More about options/useCapture.
Examples:
addEventListener(btns, "click", doIt);
addEventListener([btn1, btn2], "click", doIt);
addEventListener(".btn", "click", doIt);
addEventListener(btn, "click focus", doIt);
addEventListener(btn, "click", doIt, { passive: true });
Delegates the event handler (an equivalent to jQuery's .live()
).
Examples:
delegateEventListener(".btn", "click", doIt);
delegateEventListener(".btn", "click focus", doIt);
In order to remove event handler, use document
as a target element, e.g.:
delegateEventListener(".btn", "click", doIt); // delegate
removeEventListener(document, "click", doIt); // remove
// removing without using the callback function:
delegateEventListener(".btn", "click.btnDelegate", doIt); // delegate
removeEventListener(document, "click.btnDelegate"); // remove
Removes the event handler. More about options/useCapture.
Examples:
removeEventListener(btn); // removes all event hanlders
removeEventListener(btn, "click"); // removes 'click' event handlers
removeEventListener(".btn", "click"); // removes 'click' event handlers
removeEventListener(btn, "click.thisIsNamespace"); // removes 'click.thisIsNamespace' event hanlders handlers
removeEventListener(btn, false, doIt); // removes all event handlers that are equal to 'doIt()'
removeEventListener(btn, "click", doIt); // removes 'click' event handlers that are equal to 'doIt()'
removeEventListener(btn, false, false, { passive: false }); // removes all event handlers that were attached together with the exact provided options
Triggers the event(s). data
โ data to pass to the event handler ((e) => {e.detail}
). Data passing doesn't yet work with click|focus|blur
events.
Examples:
triggerEvent(btn, "click"); // triggers 'click' event
triggerEvent(btn, "click.thisIsNamespace"); // triggers 'click.thisIsNamespace' event
triggerEvent(btn, ".thisIsNamespace"); // triggers all events with 'thisIsNamespace' namespace
triggerEvent(btn, "customEvent"); // triggers custom event
triggerEvent(btn, "customEvent anotherCustomEvent"); // triggers custom event
triggerEvent(btn, "customEvent", "someData"); // triggers custom event and passed data
triggerEvent(btn, "customEvent", { some: "data" }); // triggers custom event and passed data
Debounces execution of a function.
Example:
window.addEventListener(
"resize",
debounce(500, () => {
// do something expensive here
})
);
Throttles execution of a function.
Example:
window.addEventListener(
"scroll",
throttle(500, () => {
// do something expensive here
})
);
Loads script file.
Returns: Promise.
Example:
loadScript("jquery.min.js", false)
.then(() => {
alert(typeof $);
})
.catch((error) => {
alert(`Error: ${error}. Try again.`);
});
Returns top/left offsets of an element
Returns: Object.
Example:
getOffset(container);
getOffset(".container");
Resolves promises sequentially.
Example:
serialPromises(
() => loadScript("jquery.min.js"),
() => loadScript("jquery-ui.min.js")
)
.then(() => {
$("ul").sortable();
})
.catch((error) => {
// error
});
Accepts String, Element, NodeList, Array and returns Array of elements.
Based on how Element.closest() works. Returns true if element
has the
closest ancestor (or itself) that matches the matches
(element|selector).
Returns an Array of parents of element
that matches the given selector
up until the until
matching element|selector.
Smart Outline hides the outline when interacting with a mouse and brings it back when interacting with a keyboard.
Inits Smart Outline. selectors
is an array of CSS selectors whose elements to affect. Default value:
```js
[
'input:focus',
'button:focus',
'textarea:focus',
'select:focus',
]
```
Temporarily reveals outline.
Halts Smart Outline.
For more functionality, consider using these vanilla JavaScript libraries:
- https://github.com/lodash/lodash (utility library) โ https://www.npmjs.com/package/common-tags (commonly used template literal tag functions)
- https://www.npmjs.com/package/nanoid (a tiny, secure, URL-friendly, unique string ID generator)
- https://allyjs.io (library simplifying certain accessibility features, functions and behaviors)
- https://github.com/mynamesleon/aria-tablist (WCAG compliant tablists, also great for accordions)
- https://github.com/davidtheclark/focus-trap (trap focus within a DOM node)
- https://github.com/edenspiekermann/a11y-toggle (accessible content toggles)
- https://github.com/GoogleChromeLabs/quicklink (faster subsequent page-loads by prefetching in-viewport links during idle time)
- https://github.com/Sjeiti/TinySort (a small script that sorts HTML elements)
- https://github.com/RubaXa/Sortable (a library for reorderable drag-and-drop lists)
- https://github.com/edenspiekermann/a11y-dialog (a very lightweight and flexible accessible modal dialog)
- https://github.com/Ghosh/micromodal (tiny javascript library for creating accessible modal dialogs)
- https://github.com/atomiks/tippyjs (highly customizable vanilla JS tooltip/popover library)
- https://github.com/FezVrasta/popper.js (a kickass library to manage your poppers)
- https://github.com/chriso/validator.js (string validators and sanitizers)
- https://scottaohara.github.io/a11y_styled_form_controls (various styled accessible form controls)
- https://github.com/jshjohnson/Choices (vanilla JS customisable select box/text input plugin)
- https://github.com/hammerjs/hammer.js (multi-touch gestures)
- https://github.com/dbushell/Pikaday (lightweight, modular CSS datepicker)
- https://github.com/flatpickr/flatpickr (lightweight, powerful javascript datetimepicker with no dependencies)
- https://basicscroll.electerious.com (parallax scrolling with CSS variables)
- https://github.com/dbrekalo/whenInViewport (handle elements as they enter viewport)
- https://github.com/KoryNunn/scroll-into-view (scrolls an element into view if possible)
- https://github.com/buzinas/simple-scrollbar (custom scrollbar cross-browser)
- https://frappe.github.io/charts (simple, responsive, modern charts library)
- https://github.com/turbolinks/turbolinks (browse the site without "hard refresh")
- https://github.com/luruke/barba.js (fluid and smooth transition between website's pages)
- https://github.com/osvaldasvalutis/accessiblenav.js (accessible multi-level dropdown menus)
- https://polished.js.org (a lightweight toolset for writing CSS in JS)
- https://www.npmjs.com/package/fitvids (responsive videos)
- https://www.npmjs.com/package/element-closest (polyfills for Element.closest and Element.matches)
- https://www.npmjs.com/package/element-remove _(polyfill for Element.remove)
- https://www.npmjs.com/package/nodelist-foreach-polyfill (polyfill for Nodelist.prototype.forEach
- https://www.npmjs.com/package/classlist-polyfill (polyfill for Element.classList)
- https://www.npmjs.com/package/array.findindex (lightweight Array.prototype.findIndex polyfill)
- https://github.com/lazd/scopedQuerySelectorShim (shims that enable the use of :scope)
- https://github.com/github/fetch (a window.fetch JavaScript polyfill)
- https://www.npmjs.com/package/custom-event-polyfill (a polyfill for CustomEvents on IE9+)
- https://www.npmjs.com/package/new-event-polyfill (new Event() polyfill)
- https://github.com/jonathantneal/svg4everybody (adds SVG External Content support to all browsers)
- https://www.npmjs.com/package/smoothscroll-polyfill (Smooth Scroll behavior polyfill)
- https://www.npmjs.com/package/element-dataset (polyfills the HTMLElement.dataset property)
- https://githubengineering.com/removing-jquery-from-github-frontend/#polyfills (a nice list of polyfills)