Dolla is a library of javascipt methods that augment existing DOM methods. Dolla is platform-agnotstic, with each method being fully tree-shakeable by any bundler. No dependencies, just helpful methods you can include as you need them.
Installation
npm install dolla
Usage
Import only the methods you use.
import {createElement} from 'dolla';
document.body.append(createElement('div', {
class: 'text-bold',
style: 'text-decoration: underline',
content: ['Hello World']
}))
addEventListenerFor (element, selector, type, listener) #
This method adds a listener callback for an Element
that is triggered when a containing target matching the selector is fired. Sets event.delegateTarget
to the element that matches to selector, while target remains as element that fired the event.
Syntax
addEventListenerFor (element, selector, type, listener)
addEventListenerFor (element, selector, type, listener, [options={}])
Arguments
element
An Element
to add the event listener to
selector
A valid CSS selector string
type
A case-sensitive string
representing the event type to listen for
listener
An Object
with a handleEvent()
method or a function
. Receives an Event
as the param. Event has attribute delegateTarget
added that is the element that matches the selector.
options
optional
An Object
with options for addEventListener
Return Value
undefined
Example
addEventListenerFor(el, 'checkbox', 'change', e => {
console.log(e.delegateTarget.value)
}, {once: true})
ancestors (element, [selector]) #
This method traverses the element and it's parents returning all ancestor elements until the selector is matched.
Syntax
ancestor (element, [selector])
ancestor (element)
Arguments
element
An Element
to add the event listener to
selector
optional
A valid CSS selector string
Return Value
An Array
of Element
ordered by closest first.
Example
ancestors(el, '.container')
append (element, content, [escape], [context], [method]) #
This method adds a listener callback for an Element
that is triggered when a containing target matching the selector is fired. Sets event.delegateTarget
to the element that matches to selector, while target remains as element that fired the event.
Syntax
append (element, content, [escape], [context], [method])
append (element, content)
append (element, content, escape)
append (element, content, context)
append (element, content, method)
Arguments
element
An Element
to add the event listener to
content
A Element
, NodeList
, HTMLCollection
, Array
, Promise
, String
of text or html, Object
passed to dolla's createElement
.
escape
optional
A Boolean
directing method to escape or not escape content that is a string
context
optional
The value to be passed as the this
parameter if content is a method
method
optional
A String
stating which method of Element
instance to use to add content. Default is "append"
Return Value
undefined
Example
append(el, el2)
append(el, [el2, el3, el4])
append(el, el2.children)
append(el, el2.childNodes)
append(el, new Promise(resolve => {
records.load().then(records => {
resolve(records.map(record => {
template(record)
}))
})
}))
append(el, {
class: 'label',
content: "Hello World"
})
append(el, "<span>Hello World</span>")
bury (object, ...keys) #
Set a value of an object following a chain of nested keys.
Syntax
bury(object, ...keys)
Arguments
object
An Object
to receive keys/value
keys
An array of Strings
to use as a chain to bury the value
Return Value
object
Example
bury({foo: 1}, 'alpha', 'beta', 'charlie', 'Hello World')
// => {
foo: 1,
alpha: {
beta: {
charlie: "Hello World"
}
}
}
content (element, content) #
This method replaces the content of an element with new content.
Syntax
content(element, content)
Arguments
element
An Element
content
A Element
, NodeList
, HTMLCollection
, Array
, Promise
, String
of text or html, Object
passed to dolla's createElement
.
Return Value
undefined
createElement (tagName="div", attributes={}) #
This method mirrors document.createElement
, but adds the ability to include attributes and content for the initialized Element
Syntax
createElement(tagName="div", attributes={})
createElement(attributes)
Arguments
tagName
optional
A String
declaring what type of HTML tag to create
attributes
optional
An Object
whose keys are used to set attributes on the created element. All HTMLElement attributes are accepted including an additional option to define content
content
: The value of the keycontent
is passed into dolla's append method. Reference theappend()
documentation for more details about possible content values.tag
: AString
declaring the type of HTML tag, used as an alternative to the first parameter
Return Value
Element
Example
createElement('table', {
class: 'uniformTable',
cellpadding: 0,
style: {
verticalAlign: 'center'
},
content: [{
tag: 'tr'
content: [{
tag: 'td',
content: 'Hello World'
}]
}]
})
css (element, rule) #
Syntax sugar for getComputedStyle
Syntax
css(element, rule)
Arguments
element
An Element
selector
A String
of a valid CSS rule
Return Value
String
representation of rule value
Example
css(el, 'width')
// => "800px"
filter (nodes, predicate) #
This method filters a NodeList
with a predicate.
Syntax
filter(nodes, predicate)
Arguments
nodes
An Array
or NodeList
predicate
A function
where parameter is each item or node of nodes. The function should return truthy to include.
Return Value
Array
Example
filter(el.childNodes, n => n.selected)
getBoundingClientRect (...elements) #
This method gets the bounding client rectangle of a group of elements. Similar to Element.getBoundingClientRect()
, but for n elements.
Syntax
getBoundingClientRect(...elements)
Arguments
elements
An Array
of Elements
Return Value
DOMRect
innerHeight (element) #
This method returns an element's height including padding
, which is excluded from el.offsetHeigh
.
Syntax
innerHeight(element)
Arguments
element
An Element
Return Value
Integer
innerWidth (element) #
This method returns an element's width including padding
, which is excluded from el.offsetWidth
.
Syntax
innerWidth(element)
Arguments
element
An Element
Return Value
Integer
insertAfter (anchor, element) #
This method appends an element after an anchor
Syntax
insertAfter(anchor, element)
Arguments
anchor
An Element
element
An Element
, NodeList
, HTMLCollection
, Array
Return Value
Integer
Example
insertAfter(document.querySelector('#anchor'), document.createElement('button'))
insertAfter(document.querySelector('#anchor'), document.querySelector('#container').children)
insertAfter(document.querySelector('#anchor'), document.querySelector('#container').childNodes)
insertAfter(document.querySelector('#anchor'), [
document.createElement('label'),
document.createElement('button')
])
insertBefore (anchor, element) #
This method appends an element after an anchor
Syntax
insertBefore(anchor, element)
Arguments
anchor
An Element
element
An Element
, NodeList
, HTMLCollection
, Array
Return Value
Integer
Example
insertBefore(document.querySelector('#anchor'), document.createElement('button'))
insertBefore(document.querySelector('#anchor'), document.querySelector('#container').children)
insertBefore(document.querySelector('#anchor'), document.querySelector('#container').childNodes)
insertBefore(document.querySelector('#anchor'), [
document.createElement('label'),
document.createElement('button')
])
isEmpty (element) #
This method returns if an element is empty
Syntax
isEmpty(element)
Arguments
element
An Element
Return Value
Boolean
isFocus (element) #
This method returns if an element is focused
Syntax
isFocus(element)
Arguments
element
An Element
Return Value
Boolean
isVisible (element) #
This method returns if an element is attached to the DOM
Syntax
isVisible(element)
Arguments
element
An Element
Return Value
Boolean
listenerElement ([tagName], [attributes], listenerType, listenerCallback) #
This method returns a HTMLElement with an event listener
Syntax
listenerElement([tagName], [attributes], listenerType, listenerCallback)
Arguments
tagName
optional
A String
for html element
attributes
optional
An Object
of attributes for dolla's createElement
listenerType
A String
representing the event type to listen to
listenerCallback
A function that receives an Event
as a parameter
Return Value
Element
Example
listenerElement('button', {
class: 'btn',
content: 'Confirm'
}, 'click', e => {
console.log(e)
})
listenerElement({
class: 'btn',
content: 'Confirm'
}, e => {
console.log(e)
})
map (elements, iteratee) #
This method returns if an element is attached to the DOM
Syntax
map(elements, iteratee)
Arguments
elements
An Array
, HTMLCollection
, NodeList
iteratee
A Function
that receives each item in elements as an argument, the return of which is set as the index of the return array
Return Value
Array
Example
map(element.children, el => el.offsetHeight)
map(element.childNodes, el => el.offsetHeight)
map([
el1,
el2,
el3
], el => el.offsetHeight)
nextElementSiblings (element, filter) #
This method returns an element's following siblings.
Syntax
nextElementSibling(element, filter)
Arguments
element
An Element
filter
A method that receives the next sibling as a paramter, and returns true or false
Return Value
Array
Example
nextElementSiblings(el, sibling => {
return sibling.tagName == "checkbox"
})
offset (element) #
This method returns an element's DOMRect
in relation to it's offsetParent
Syntax
offset(element)
Arguments
element
An Element
or HTMLCollection
Return Value
DOMRect
offsetTo (element, target) #
This method returns an elements position {top, left}
in relation to a target element
Syntax
offsetTo(element, target)
Arguments
element
An Element
or HTMLCollection
target
An Element
Return Value
DOMRect
offsetToBody (element) #
This method returns an element's bounding DOMRect
in relation to the rootNode (typically document.body
)
Syntax
offsetToBody(element)
Arguments
element
An Element
or HTMLCollection
Return Value
DOMRect
offsetToViewport (element) #
This method returns an elements position {top, left}
in relation to the viewport
Syntax
offsetToViewport(element)
Arguments
element
An Element
or HTMLCollection
Return Value
DOMRect
outerHeight (element) #
This method returns the height of an element including margin
Syntax
outerHeight(element)
Arguments
element
An Element
Return Value
Integer
outerWidth (element) #
This method returns the width of an element including margin
Syntax
outerWidth(element)
Arguments
element
An Element
Return Value
Integer
prepend (element, content) #
This method is a same as append
, but inserts content at the start of an elements children.
Syntax
prepend (element, content)
prepend (element, content, escape)
prepend (element, content, context)
prepend (element, content, method)
prepend (element, content, escape, context, method)
Arguments
element
An Element
to add the event listener to
content
A Element
, NodeList
, HTMLCollection
, Array
, Promise
, String
of text or html, Object
passed to dolla's createElement
.
escape
optional
A Boolean
directing method to escape or not escape content that is a string
context
optional
The value to be passed as the this
parameter if content is a method
method
optional
A String
stating which method of Element
instance to use to add content. Default is "append"
Return Value
undefined
Example
prepend(el, el2)
prepend(el, [el2, el3, el4])
prepend(el, el2.children)
prepend(el, el2.childNodes)
prepend(el, new Promise(resolve => {
records.load().then(records => {
resolve(records.map(record => {
template(record)
}))
})
}))
prepend(el, {
class: 'label',
content: "Hello World"
})
prepend(el, "<span>Hello World</span>")
previousElementSiblings (element, filter) #
This method returns an element's previous siblings.
Syntax
previousElementSiblings(element, filter)
Arguments
element
An Element
filter
A method that receives the previous sibling as a paramter, and returns true or false
Return Value
Array
Example
previousElementSiblings(el, sibling => {
return sibling.tagName == "checkbox"
})
remove (element) #
This method removes an element from the document/fragment to which it is attached
Syntax
remove(element)
Arguments
element
An Element
Return Value
Element
replaceContents (element, ...nodes) #
This method replaces an element's content with new content
Syntax
remove(element, ...nodes)
Arguments
element
An Element
nodes
A Element
, NodeList
, HTMLCollection
, Array
, Promise
, String
of text or html, Object
passed to dolla's createElement
. Checkout append
for more details about what content can be used
Return Value
undefined
Example
replaceContents(el, anotherElement.children)
replaceContents(el, {
tag: 'button',
class: 'btn'
})
serializeForm (form) #
This method returns object of a form element's key and value pairs
Syntax
serializeForm(form)
Arguments
form
An FormElement
Return Value
Object
Example
<form>
<input name="user[name]" />
<input name="user[email_address]" />
<input name="team[is_active]" />
</form>
serializeForm(form)
// => {
// [user]name: 'Rod Kimble',
// [user]emailAddress: 'rod.kimble@hot-rod-productions.com',
// [team][is_active]: true
//}
serializeFormToJSON (form) #
This method returns JSON of a form element's key and value pairs. This function unlike serializeForm
allows the keys to nest keys (see usage)
Syntax
serializeFormToJSON(form)
Arguments
form
An FormElement
Return Value
JSON
Example
<form>
<input name="user[name]">
<input name="user[email_address]">
<input name="team[is_active]">
</form>
serializeForm(form)
// => {
// user: {
// name: 'Rod Kimble',
// emailAddress: 'rod.kimble@hot-rod-productions.com'
// },
// team: {
// is_active: true
// }
//}
setAttributes (el, attributes={}) #
Assigns attributes and content for an Element
Syntax
assignAttributes(el, attributes={})
Arguments
el
An Element
to assign attributes too
attributes
optional
An Object
whose keys are used to set attributes on the created element. All HTMLElement attributes are accepted including an additional option to define content
content
: The value of the keycontent
is passed into dolla's append method. Reference theappend()
documentation for more details about possible content values.tag
: AString
declaring the type of HTML tag, used as an alternative to the first parameter
Return Value
Element
Example
assignAttributes(el, {
class: 'uniformTable',
cellpadding: 0,
style: {
verticalAlign: 'center'
},
content: [{
tag: 'tr'
content: [{
tag: 'td',
content: 'Hello World'
}]
}]
})
stateAttribute (value) #
Initializes StateBus with value
Syntax
stateAttribute(value)
Arguments
value
Initial value of attribute
Return Value
StateBus
Example
const el = createElement('button')
const isOpen = stateAttribute(true)
isOpen.addListener(v => el.disabled = v.value)
StateBus (value) #
StateBus is a simple javascript class that hold a value and calls listener callbacks when it changes
Syntax
new StateBus(value)
Constructor
value
Initial value of attribute
Return Value
StateBus
Example
const el = createElement('button')
const isOpen = new StateBus(true)
isOpen.addListener(v => el.disabled = v.value)
Instance Methods
get()
Returns value
set(v)
Sets state
addListener(callback:function)
Add listener
removeListener(callback:function)
Remove Listener
valueOf()
Returns value
transform(transformation:function)
Returns a new StateBus that follows changes to this StateBus, with the transformation applied to value everytime it changes
StuckObserver (options={}) #
Extends IntersectionObserver to default callback to toggle a desigated class when element is stuck
Syntax
const observer = new StuckObserver(options={})
const el = createElement({style: {position: 'sticky', top: 0}})
observer.observe(el)
Constructor
options
root
Same as IntersectionObserver
top
Number | pixel inset into root to determine sticky state, default: 1
right
Number | pixel inset into root to determine sticky state, default: -9999, which essentially removes it as a boundary
bottom
Number | pixel inset into root to determine sticky state, default: -9999, which essentially removes it as a boundary
left
Number | pixel inset into root to determine sticky state, default: -9999, which essentially removes it as a boundary
class
String | class to toggle, when stuck, class is added, default: stuck
Return Value
StuckObserver
Instance Methods
Inherits from IntersectionObserver
toElements (content) #
This method converts a string of HTML to Elements
Syntax
toElements(content)
Arguments
content
A String
of HTML or a Function
that retuns a string of HTML
Return Value
NodeList
Example
toElements("<div class='container'><label>Label</label><input type='checkbox'></div>")
toElements(() => "<div class='container'><label>Label</label><input type='checkbox'></div>")
trigger (element, eventName) #
This method calls an element's dispatchEvent
with a custom event.
Syntax
trigger(element, eventName)
Arguments
element
An Element
eventName
A String
representing the event type
options
Object passed to CustomEvent constructor. Defaults target
, bubbles
, cancelable
Return Value
false
if event is cancelable, and at least one of the event handlers which received event called Event.preventDefault()
. Otherwise true
.
Example
el.addEventListener('attachedToDOM', e => el.style.background = 'green')
trigger(el, 'attachedToDOM')
Contributors
Bug Reporting
Please report bugs in GitHub Issues
Licensing
Uniform is released under the MIT License