Utilities for clientside code injection
const {
replace,
insertBefore,
insertAfter,
appendChild,
onEvent,
style,
onEnterViewport,
restoreAll
} = require('@qubit/utils/dom')()
Replaces target
with el
, returns a function that swaps the elements back round.
e.g.
const restore = replace(target, el)
Appends el
to the end of target
's list of children, returns a function that removes el
e.g.
const restore = appendChild(target, el)
Inserts el
before target
, returns a function that removes el
e.g.
const restore = insertBefore(target, el)
Inserts el
after target
, returns a function that removes el
e.g.
const restore = insertAfter(target, el)
Adds an event listener of type
to el
, returning a function that removes it. If you omit the callback, the function returns a promise. You should use restoreAll to restore in this case.
e.g.
const restore = onEvent(el, 'click', cb)
onEvent(el, 'click').then(fn)
function cb () {
window.alert('clicked!')
}
Calls callback when el
enters the viewport, returns a function that cancels and removes any event listeners. If you omit the callback, the function returns a promise. You should use restoreAll to restore in this case.
It accepts a third optional parameter scrollTargetEl
which represents the element where the scroll listener will be attached. If not specified window
will be used.
e.g.
const restore = onEnterViewport(el, cb)
onEnterViewport(el).then(cb)
function cb () {
window.alert('Hello from viewport!')
}
// With multiple elements
const restore = onEnterViewport([el1, el2], cb)
onEnterViewport([el1, el2]).then(cb)
function cb () {
window.alert('Hello from viewport!')
}
Merges specified styles to el
, returning a function that reverts your changes.
Styles can be specified in either camel case or kebab case and can be provided either as a string or an object.
e.g.
const restore = style(el, {
height: '10px',
backgroundColor: 'red'
})
// or
const restore = style(
el,
`
background-color: red;
height: 10px;
`
)
Calls all dispose functions that got generated by using the other methods. e.g.
replace(target, el)
onEvent(el, 'click', handler)
restoreAll()
// Equivalent to:
const restore1 = replace(target, el)
const restore2 = onEvent(el, 'click', handler)
restore1()
restore2()
Traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.
Functionality is the same as described in https://developer.mozilla.org/en-US/docs/Web/API/Element/closest but this is a function that takes an element as the first argument rather than a method called on a DOM node. e.g.
const closestElement = closest(targetElement, selectors)