a lightweight DOM manipulation library with jQuery-inspired "fluent" API
The use of jQuery makes DOM manipulation code compact and legible - but it is a rather large library with many no longer required features. The idea behind dommali
(pronounced "dom-ma-li") is to create a thin layer on top of the API of modern browsers (excluding MS IE and "classic" MS Edge!) that still allows code to be as concise as jQuery would do.
dommali
was inspired by nanoJS and femtoJS - and like those, its implementation is so simple that it is not too difficult to add new methods or remove unwanted ones in order to enhance functionality or reduce size.
Important: dommali
is no drop-in replacement for jQuery! If you need something like that, look for Zepto.js, Cash, UmbrellaJS, Chibi or similar
The most notable differences between dommali
and jQuery (or a look-alike) are:
- iterator callback functions do not bind
this
to the DOM element just processed, instead they get a correspondingdommali
object as their first argument - as a consequence, "fat arrow" functions may more easily serve as callbacks - methods retrieving the current size and position of a DOM element have specific names which makes their intention more obvious particularly for casual programmers: f.e.,
positionInViewport
vs.positionInParent
vs.positionOnPage
- additionally, some methods have names (or synonyms) which indicate whether they return layout or render measures: layout positions and dimensions are used by the browser layout engine and do not consider any CSS transforms applied to DOM elements, whereas render measures take such transforms into account
dommali
does not define its own event object - nowadays, creating DOM events is so simple that there is just no need for a wrapper. It does, however, supportextraParameters
passed when triggering an event and Eventdata
specified while registering an event handler- within asynchronous functions it is possible to
waitFor
the arrival of an event or to write loops thatrepeatUntil
a given event arrives - both functions may also be provided with a timeout in order to prevent waiting or looping forever - event handler registrations support the special "selector"
@this
which effectively prevents the handler from being invoked by bubbling events - both event handler management functions and
waitFor
orrepeatUntil
support anchored events, i.e., event names followed by a CSS selector which restricts the events to be handled to those triggered on specific elements only dommali
does not support CSS animations but animated CSS transitions - and those are really simple
NPM users: please consider the Github README for the latest description of this package (as updating the docs would otherwise always require a new NPM package version)
Just a small note: if you like this module and plan to use it, consider "starring" this repository (you will find the "Star" button on the top right of this page), so that I know which of my repositories to take most care of.
Here are the methods provided by dommali
in alphabetical order:
dommali
may be used as an ECMAScript module (ESM), a CommonJS or AMD module or from a global variable.
You may either install the package into your build environment using NPM with the command
npm install dommali
or load the plain script file directly
<script src="https://unpkg.com/dommali"></script>
How to access the package depends on the type of module you prefer
- ESM (or Svelte):
import dommali from 'dommali'
- CommonJS:
const dommali = require('dommali')
- AMD:
require(['dommali'], (dommali) => {...})
Alternatively, you may access the global variable dommali
directly.
For Svelte, it is recommended to import the package in a module context. From then on, its exports may be used as usual:
<script context="module">
import dommali from 'dommali'
</script>
<script>
const $ = dommali // make "dommali" calls look like "jQuery" ones
$(document.body).html('<h1>Hello, World!</h1>')
</script>
Let's assume that you already "required" or "imported" (or simply loaded) the module according to your local environment. In that case, you may use it as follows:
const $ = dommali // make "dommali" calls look like "jQuery" ones
$(document.body).html('<h1>Hello, World!</h1>')
Similar to jQuery, dommali
objects (i.e., instances of type DOMMaLi
) represent collections of zero, one or multiple DOM elements. Internally, these elements may not be listed in document order unless they have been found by a CSS query or retrieved as the children of another element. While dommali
objects may represent DOM elements of any type, some methods only work on items of type HTMLElement
(other elements will be ignored) - those methods are explicitly marked in their description.
The signatures shown below are those used by TypeScript
dommali():DOMMaLi
returns a new emptydommali
object, i.e., one that represents no DOM elementdommali(startup:Function):typeof DOMMaLi
is a shortcut forDOMMaLi.ready(startup)
(see below)dommali(selector:string):DOMMaLi
returns adommali
object representing all DOM elements matching the given CSS selectordommali(html:string):DOMMaLi
returns a newdommali
object representing all DOM elements created from the given HTML codedommali(element:Element):DOMMaLi
returns a newdommali
object representing the given DOM elementdommali(elements:Element[]):DOMMaLi
returns a newdommali
object representing the given DOM elements (in the given order)dommali(bridge:DOMMaLi):DOMMaLi
returns a duplicate of the givendommali
object
DOMMaLi.extraParametersOfEvent(Event:Event):any[]
returns the (possible empty) list of additional arguments passed when the givenEvent
was triggered (seetrigger
)DOMMaLi.ready(startup:Function):typeof DOMMaLi
registers a function which is to be called as soon as the DOM is ready (i.e., all DOM elements are present although images and other resources may not be completely loaded). If the DOM is ready at the moment the startup functions wants to be registered, it will be invoked immediately. It is safe to register new startup functions at any time - even while they are being executedDOMMaLi.textHeight(Text:string, TemplateOrSettings?:any):number
returns the height of a givenText
(in pixels) when rendered in a givendommali
object, a given DOM element or in its own DOM element with given CSS settings. For that purpose, the optionalTemplateOrSettings
argument may contain either adommali
object, a DOM element or a plain JavaScript object with one or multiple "relevant" CSS settings. Relevant CSS settings includefont-family
,font-size
,font-weight
,font-style
,font-variant
,font-variant-caps
,font-variant-numeric
,font-variant-alternates
,font-variant-ligatures
,font-variant-east-asian
,font-stretch
,font-kerning
,font-size-adjust
,font-synthesis
,font-language-override
,white-space
,letter-spacing
,word-spacing
,text-indent
,text-transform
,word-break
,line-break
,line-height
andwidth
- other CSS settings will be ignored. Please note, that you may specify a desired textwidth
explicity in order to enforce line wrapping of long textsDOMMaLi.textWidth(Text:string, TemplateOrSettings?:any):number
returns the width of a givenText
(in pixels) when rendered in a givendommali
object, a given DOM element or in its own DOM element with given CSS settings. For that purpose, the optionalTemplateOrSettings
argument may contain either adommali
object, a DOM element or a plain JavaScript object with one or multiple "relevant" CSS settings. Relevant CSS settings includefont-family
,font-size
,font-weight
,font-style
,font-variant
,font-variant-caps
,font-variant-numeric
,font-variant-alternates
,font-variant-ligatures
,font-variant-east-asian
,font-stretch
,font-kerning
,font-size-adjust
,font-synthesis
,font-language-override
,white-space
,letter-spacing
,word-spacing
,text-indent
andtext-transform
- other CSS settings will be ignored
get length ():number
contains the number of DOM elements represented by thisdommali
objectsize ():number
returns the number of DOM elements represented by thisdommali
objectisEmpty ():boolean
returnstrue
if thisdommali
object does not represent any DOM element - orfalse
otherwisesubjects ():Element[]
returns a copy of the list of DOM elements represented by thisdommali
objectsubject (Index:number):Element|undefined
returns the single item found at indexIndex
in the list of DOM elements represented by thisdommali
object - orundefined
if no such item existsindexOf (Value:Element|DOMMaLi):number
looks for the given DOM element or the first element represented by the givendommali
object in the list of DOM elements represented by thisdommali
object and returns its index - or-1
if the element can not be found
slice (start?:number, end?:number):DOMMaLi
returns a newdommali
object representing all items from the list of DOM elements represented by thisdommali
object starting at indexstart
and ending before indexend
(or until the end of the list, ifend
was omitted). If bothstart
andend
are missing, thisdommali
object is simply duplicatedfirst ():DOMMaLi
returns a newdommali
object representing the first element from the list of DOM elements represented by thisdommali
object - or any emptydommali
object if this one is empty as welllast ():DOMMaLi
returns a newdommali
object representing the last element from the list of DOM elements represented by thisdommali
object - or any emptydommali
object if this one is empty as welleq (Index:number):DOMMaLi
returns a newdommali
object representing the element at indexIndex
from the list of DOM elements represented by thisdommali
object - or any emptydommali
object if no such element exists
forEach (Callback:(Item:DOMMaLi, Index:number, Container:DOMMaLi) => any):DOMMaLi
iterates over all DOM elements represented by thisdommali
object and invokes the givenCallback
function with the following arguments:
adommali
object representing the current DOM element, its index in the list of DOM elements represented by thisdommali
object and that object itself. In contrast to jQuery and many other similar libraries,this
is not bound to the current DOM element - this simplifies the use of "fat arrow" functions as callbacksfilter (Selector:string|String):DOMMaLi
returns a newdommali
object representing only those DOM elements from thisdommali
object which match the given CSS selectorfilter (Callback:(Item:DOMMaLi, Index:number, Container:DOMMaLi) => boolean):DOMMaLi
returns a newdommali
object representing only those DOM elements from thisdommali
object for which the givenCallback
function returns true. This function is invoked with the following arguments:
adommali
object representing the current DOM element, its index in the list of DOM elements represented by thisdommali
object and that object itself. In contrast to jQuery and many other similar libraries,this
is not bound to the current DOM element - this simplifies the use of "fat arrow" functions as callbacks
matches (Selector:string|String):boolean
returnstrue
if the first DOM element represented by thisdommali
object matches the given CSS selector - orfalse
otherwisefind (Selector:string|String):DOMMaLi
returns a new (and possibly empty)dommali
object representing all those DOM elements within the scope of thisdommali
object that match the given CSS selectorfindFirst (Selector:string|String):DOMMaLi
returns a new (and possibly empty)dommali
object representing the first DOM element within the scope of thisdommali
object that matches the given CSS selector
positionInViewport ():{ left:number,top:number }|undefined
returns the rendering position of the first DOM element represented by thisdommali
object relative to the current viewport (orundefined
if thisdommali
object is empty)renderPositionInViewport ():{ left:number,top:number }|undefined
is just a synonym forpositionInViewport
, emphasizing the fact, that the rendering position is returned (which depends of CSS transforms for that DOM element)positionInParent ():{ left:number,top:number }|undefined
returns the layout position of the first HTML element represented by thisdommali
object relative to its "offset parent" (orundefined
if either thisdommali
object is empty, its first element is not an HTML element or no offset parent could be found)layoutPositionInParent ():{ left:number,top:number }|undefined
is just a synonym forpositionInParent
, emphasizing the fact, that the layout position is returned (which is independent of any DOM element CSS transforms)positionOnPage ():{ left:number,top:number }|undefined
returns the layout position of the first DOM element represented by thisdommali
object relative to the document (orundefined
if thisdommali
object is empty or its first element is not an HTML element)layoutPositionOnPage ():{ left:number,top:number }|undefined
is just a synonym forpositionOnPage
, emphasizing the fact, that the layout position is returned (which is independent of any DOM element CSS transforms)width (newValue?:number):number|DOMMaLi|undefined
if nonewValue
is given, this method returns the layout width of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty or its first element is not an HTML element). Otherwise, the layout width of all HTML elements represented by thisdommali
object is set to thenewValue
pixelsheight (newValue?:number):number|DOMMaLi|undefined
if nonewValue
is given, this method returns the layout height of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty or its first element is not an HTML element). Otherwise, the layout height of all HTML elements represented by thisdommali
object is set to thenewValue
pixelslayoutWidth (newValue?:number):number|DOMMaLi|undefined
is just a synonym forwidth
, emphasizing the fact, that the layout width is returned or set (which is independent of any DOM element CSS transforms)layoutHeight (newValue?:number):number|DOMMaLi|undefined
is just a synonym forheight
, emphasizing the fact, that the layout height is returned or set (which is independent of any DOM element CSS transforms)outerWidth (newValue?:number):number|DOMMaLi|undefined
is just a synonym forwidth
, emphasizing the fact, that the returned width includes the element's padding and borderouterHeight (newValue?:number):number|DOMMaLi|undefined
is just a synonym forheight
, emphasizing the fact, that the returned height includes the element's padding and borderrenderWidth ():number|undefined
returns the render width of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). The result is affected by any CSS transforms for that elementrenderHeight ():number|undefined
returns the render height of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). The result is affected by any CSS transforms for that elementinnerWidth ():number|undefined
returns the "inner" layout width of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty) without border, padding and scrollbarsinnerHeight ():number|undefined
returns the "inner" layout height of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty) without border, padding and scrollbars
parent ():DOMMaLi
returns a newdommali
object representing the "parent" of the first DOM element represented by thisdommali
object (or an emptydommali
object if this one is empty as well)closest (Selector:string|String):DOMMaLi
returns a newdommali
object representing the innermost element among the first DOM element represented by thisdommali
object and its parents, that matches the givenSelector
(or an emptydommali
object if either this one is empty or no matching DOM element could be found)isAttached ():boolean
returnstrue
, if the first DOM element represented by thisdommali
object is part of the document - orfalse
otherwisecontains (Candidate:DOMMaLi):boolean
returnstrue
, if the first DOM element represented by thisdommali
object contains the first DOM element represented by the givenCandidate
- orfalse
otherwisechildren (Selector?:string|String):DOMMaLi
ifSelector
is missing, this method returns a newdommali
object representing all direct "children" of the first DOM element represented by thisdommali
object. Otherwise, the newdommali
object represents only those children which also match the given CSSSelector
firstChild (Selector?:string|String):DOMMaLi
ifSelector
is missing, this method returns a newdommali
object representing the first direct "child" of the first DOM element represented by thisdommali
object. Otherwise, the newdommali
object represents the first child which also matches the given CSSSelector
lastChild (Selector?:string|String):DOMMaLi
ifSelector
is missing, this method returns a newdommali
object representing the last direct "child" of the first DOM element represented by thisdommali
object. Otherwise, the newdommali
object represents the last child which also matches the given CSSSelector
prev (Selector?:string|String):DOMMaLi
ifSelector
is missing, this method returns a newdommali
object representing the immediately preceding "sibling" of the first DOM element represented by thisdommali
object - i.e., the direct child of that element's parent, which immediately precedes it. Otherwise, the newdommali
object represents the nearest preceding "sibling" which also matches the given CSSSelector
next (Selector?:string|String):DOMMaLi
ifSelector
is missing, this method returns a newdommali
object representing the immediately following "sibling" of the first DOM element represented by thisdommali
object - i.e., the direct child of that element's parent, which immediately follows it. Otherwise, the newdommali
object represents the nearest following "sibling" which also matches the given CSSSelector
show ():DOMMaLi
makes all HTML elements represented by thisdommali
object (potentially) visible by setting their CSS propertydisplay
to a value different fromnone
- if possible,dommali
tries to restore any setting that was active before an element was hidden. Otherwise, it uses the default setting for the given element tag - orblock
if all failshide ():DOMMaLi
makes all HTML elements represented by thisdommali
object invisible by setting their CSS propertydisplay
tonone
scrollLeft (newValue?:number):number|DOMMaLi|undefined
if nonewValue
is given, this method returns the number of pixels by which the first DOM element represented by thisdommali
object is scrolled from its left edge (orundefined
if thisdommali
object is empty) Otherwise, it scrolls all DOM elements represented by thisdommali
object to a positionnewValue
pixels from their left edgescrollTop (newValue?:number):number|DOMMaLi|undefined
if nonewValue
is given, this method returns the number of pixels by which the first DOM element represented by thisdommali
object is scrolled from its top edge (orundefined
if thisdommali
object is empty) Otherwise, it scrolls all DOM elements represented by thisdommali
object to a positionnewValue
pixels from their top edgescrollWidth ():number|undefined
returns the width of the contents of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty), including content not visible due to an overflowscrollHeight ():number|undefined
returns the height of the contents of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty), including content not visible due to an overflowscrollTo (x:number, y:number, Mode:'instant'|'smooth'|'auto' = 'auto'):DOMMaLi
scrolls all DOM elements represented by thisdommali
object to a positionx
pixels from their left andy
pixels from their top edge. If given,Mode
specifies whether the scrolling should animate smoothly or happen instantly in a single jump
hasClass (Classes:string):boolean
returnstrue
if the first DOM element represented by thisdommali
object is associated with all (space-separated) CSS classes given byClasses
- orfalse
otherwiseaddClass (Classes:string):DOMMaLi
associates all DOM elements represented by thisdommali
object with the (space-separated) CSS classes given byClasses
toggleClass (Classes:string):DOMMaLi
toggles the association of all DOM elements represented by thisdommali
object with the (space-separated) CSS classes given byClasses
removeClass (Classes:string):DOMMaLi
removes the association of all DOM elements represented by thisdommali
object with the (space-separated) CSS classes given byClasses
append (Content:string|String|DOMMaLi|Element|Element[]):DOMMaLi
ifContent
contains HTML code, this method inserts the DOM elements repeatedly created based onContent
at the end of every DOM element represented by thisdommali
object - otherwise the DOM elements given byContent
are inserted at the end of the first DOM element represented by thisdommali
object only.Content
may contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommali
objectprepend (Content:string|String|DOMMaLi|Element|Element[]):DOMMaLi
ifContent
contains HTML code, this method inserts the DOM elements repeatedly created based onContent
at the beginning of every DOM element represented by thisdommali
object - otherwise the DOM elements given byContent
are inserted at the beginning of the first DOM element represented by thisdommali
object only.Content
may contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommali
objectinsertAfter (Content:DOMMaLi):DOMMaLi
inserts all DOM elements represented by thisdommali
object after the first DOM element represented by the givenContent
.Content
may contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommali
objectinsertBefore (Content:DOMMaLi):DOMMaLi
inserts all DOM elements represented by thisdommali
object before the first DOM element represented by the givenContent
.Content
may contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommali
objectreplaceWith (Replacement:string|String|DOMMaLi|Element|Element[]):void
ifContent
contains HTML code, this method replaces every DOM element represented by thisdommali
object by the DOM elements repeatedly created based onContent
- otherwise the first DOM element represented by thisdommali
object is replaced by the DOM elements given byContent
.Content
may contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommali
objectremove ():DOMMaLi
removes all DOM elements represented by thisdommali
object
prop (Property:string, newValue?:any):DOMMaLi|any|undefined
if nonewValue
is given, this method returns the value of propertyProperty
of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). Otherwise, propertyProperty
of all DOM elements represented by thisdommali
object is set tonewValue
hasProp (Property:string):boolean
returnstrue
if propertyProperty
is found in the first DOM element represented by thisdommali
object - orfalse
otherwiseremoveProp (Property:string):DOMMaLi
removes propertyProperty
from all DOM elements represented by thisdommali
object
data (Key:string, newValue?:any):DOMMaLi|any|undefined
if nonewValue
is given, this method returns the value of data entryKey
of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). Otherwise, data entryKey
of all DOM elements represented by thisdommali
object is set tonewValue
. Data entries are custom values of any JavaScript type stored in DOM elements without polluting their namespace or overwriting DOM element properties or methodshasData (Key:string):boolean
returnstrue
if data entryKey
is found in the first DOM element represented by thisdommali
object - orfalse
otherwiseremoveData (Key:string):DOMMaLi
removes data entryKey
from all DOM elements represented by thisdommali
object
attr (Attribute:string, newValue?:any):DOMMaLi|string|undefined
if nonewValue
is given, this method returns the value of HTML attributeAttribute
of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). Otherwise, the HTML attributeAttribute
of all DOM elements represented by thisdommali
object is set tonewValue
hasAttr (Attribute:string):boolean
returnstrue
if HTML attributeAttribute
is found in the first DOM element represented by thisdommali
object - orfalse
otherwiseremoveAttr (Attribute:string):DOMMaLi
removes HTML attributeAttribute
from all DOM elements represented by thisdommali
object
css (Property:string|string, newValue?:string):DOMMaLi|string|undefined
if nonewValue
is given, this method returns the computed value of CSS propertyProperty
of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). Otherwise, the CSS propertyProperty
of all DOM elements represented by thisdommali
object is set tonewValue
css (PropertyList:string[]):PlainObject|undefined
returns the computed values of all CSS properties given byPropertyList
of the first DOM element represented by thisdommali
object as a plain JavaScript object with the given property names as keys (orundefined
if thisdommali
object is empty)css (PropertySet:PlainObject):DOMMaLi
sets the CSS properties given by the keys ofPropertySet
of all DOM elements represented by thisdommali
object to the values specified inPropertySet
html (newValue?:string):DOMMaLi|string|undefined
if nonewValue
is given, this method returns the inner HTML of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). Otherwise, the inner HTML of all DOM elements represented by thisdommali
object is set tonewValue
text (newValue?:string):DOMMaLi|string|undefined
if nonewValue
is given, this method returns the inner text of the first DOM element represented by thisdommali
object (orundefined
if thisdommali
object is empty). Otherwise, the inner text of all DOM elements represented by thisdommali
object is set tonewValue
appendText (Value:string):DOMMaLi
inserts the text given byValue
after the inner text of all DOM elements represented by thisdommali
objectprependText (Value:string):DOMMaLi
inserts the text given byValue
before the inner text of all DOM elements represented by thisdommali
object
on (anchoredEvent:string, Handler:Function):DOMMaLi
registers the given event handlerHandler
for the eventanchoredEvent
in all DOM elements represented by thisdommali
object.Handler
will be invoked whenever the givenEvent
is triggered on the given "anchor" as seen from these DOM elements (provided that the event is allowed to "bubble" if the anchor is a descendant of a given DOM object). IfHandler
returns the explicit valuefalse
,Event.stopPropagation()
andEvent.preventDefault()
are called for the current eventon (Events:string, Handler:Function):DOMMaLi
registers the given event handlerHandler
for every event in the (space-separated) list given byEvents
in all DOM elements represented by thisdommali
object.Handler
will be invoked whenever one of the givenEvents
is triggered on one of these DOM elements themselves or one of their descendants (if the event is allowed to "bubble"). IfHandler
returns the explicit valuefalse
,Event.stopPropagation()
andEvent.preventDefault()
are called for the current eventon (Events:string, Selector:string|String|null, Handler:Function):DOMMaLi
registers the given event handlerHandler
as a "delegated event handler" for every event in the (space-separated) list given byEvents
in all DOM elements represented by thisdommali
object.Handler
will be invoked whenever one of the givenEvents
is triggered on one of these DOM elements themselves or one of their descendants (if the event is allowed to "bubble") - provided that the original event target matches the given CSSSelector
. SettingSelector
tonull
simply skips the matching. IfHandler
returns the explicit valuefalse
,Event.stopPropagation()
andEvent.preventDefault()
are called for the current eventon (anchoredEvent:string, Data:any, Handler:Function):DOMMaLi
registers the given event handlerHandler
for the eventanchoredEvent
in all DOM elements represented by thisdommali
object.Handler
will be invoked whenever the givenEvent
is triggered on the given "anchor" as seen from these DOM elements (provided that the event is allowed to "bubble" if the anchor is a descendant of a given DOM object). Additionally, propertydata
of the incoming event is set toData
before the registered handler is called. IfHandler
returns the explicit valuefalse
,Event.stopPropagation()
andEvent.preventDefault()
are called for the current eventon (Events:string, Selector:string|String|null, Data:any, Handler:Function):DOMMaLi
registers the given event handlerHandler
(as a "delegated event handler" ifSelector
is notnull
) for every event in the (space-separated) list given byEvents
in all DOM elements represented by thisdommali
object.Handler
will be invoked whenever one of the givenEvents
is triggered on one of these DOM elements themselves or one of their descendants (if the event is allowed to "bubble") - provided that the original event target matches the given CSSSelector
. Additionally, propertydata
of the incoming event is set toData
before the registered handler is called. SettingSelector
tonull
simply skips the matching. IfHandler
returns the explicit valuefalse
,Event.stopPropagation()
andEvent.preventDefault()
are called for the current event
once (Events:string, Handler:Function):DOMMaLi
behaves likeonce(Events,Handler)
, but automatically unregisters the givenHandler
upon its first invocationonce (anchoredEvent:string, Handler:Function):DOMMaLi
behaves likeonce(anchoredEvent,Handler)
, but automatically unregisters the givenHandler
upon its first invocationonce (Events:string, Selector:string|String|null, Handler:Function):DOMMaLi
behaves likeonce(Events,Selector,Handler)
, but automatically unregisters the givenHandler
upon its first invocationonce (anchoredEvent:string, Data:any, Handler:Function):DOMMaLi
behaves likeonce(anchoredEvent,Data,Handler)
, but automatically unregisters the givenHandler
upon its first invocationonce (Events:string, Selector:string|String|null, Data:any, Handler:Function):DOMMaLi
behaves likeonce(Events,Selector,Data,Handler)
, but automatically unregisters the givenHandler
upon its first invocation
off ():DOMMaLi
unregisters all event handlers registered in all DOM elements represented by thisdommali
objectoff (anchoredEvent:string):DOMMaLi
unregisters all event handlers registered for the givenanchoredEvent
in all DOM elements represented by thisdommali
objectoff (Events:string):DOMMaLi
unregisters all event handlers registered for every event in the (space-separated) list given byEvents
in all DOM elements represented by thisdommali
objectoff (Events:string, Selector:string|String|null):DOMMaLi
unregisters all event handlers registered as delegated event handlers with CSS selectorSelector
for every event in the (space-separated) list given byEvents
in all DOM elements represented by thisdommali
objectoff (anchoredEvent:string, Handler:Function):DOMMaLi
unregisters the givenHandler
registered for the givenanchoredEvent
in all DOM elements represented by thisdommali
objectoff (Events:string, Selector:string|String|null, Handler:Function):DOMMaLi
unregisters the givenHandler
registered as delegated event handler with CSS selectorSelector
for every event in the (space-separated) list given byEvents
in all DOM elements represented by thisdommali
object
repeatUntil (...anchoredEventsOrTimeoutOrLoopBody:(string|number|Function)[]):Promise<any>
returns a promise which resolves after one of the givenanchoredEvents
has been received or the number of milliseconds given by aTimeout
have passed. Until then, the given (asynchronous)LoopBody
function will be executed as often as possible. IfLoopBody
returns any other value butundefined
, the loop is terminated and the promise resolves to the loop body's return value. After receiving an event,repeatUntil
resolves to that event as soon asLoopBody
has finished; in case of a timeout it resolves to the actual number of milliseconds that have passed since the initial invocation (this number is usually slightly higher than the specified timeout) - but again, only afterLoopBody
has finished. All arguments exceptLoopBody
are optional - callingrepeatUntil
solely with aLoopBody
simply repeatedly executes that function until it returns a value different fromundefined
(see Notes onrepeatUntil
)trigger (Event:string|Event, extraParameters?:any[]):boolean
fires the givenEvent
on all DOM elements represented by thisdommali
object. IfEvent
is given as a string, aCustomEvent
of typeEvent
is created and fired. The optional argumentextraParameters
may be a single value or a list of values which are passed as additional arguments (after the event object itself) to the Handler.trigger
returnsfalse
if at least one of the invoked event handlers calledEvent.preventDefault()
ortrue
otherwisewaitFor (...anchoredEventsOrTimeout:(string|number)[]):Promise<any>
returns a promise which resolves as soon as one of the givenanchoredEvents
has been received or the number of milliseconds given by aTimeout
have passed. All arguments are optional - callingwaitFor
without any arguments just resolves immediately. After receiving an event,waitFor
resolves to that event; in case of a timeout it resolves to the actual number of milliseconds that have passed since the initial invocation (this number is usually slightly higher than the specified timeout) (see Notes onwaitFor
)
focus ():DOMMaLi
grants the keyboard focus to the first DOM element represented by thisdommali
object - provided that this is an HTML element and is allowed to be focused. Otherwise,focus
does nothingblur ():DOMMaLi
removes the keyboard focus from the first DOM element represented by thisdommali
object - provided that this is an HTML element and is currently focused. Otherwise,blur
does nothinghasFocus ():boolean
returnstrue
, if the first DOM element represented by thisdommali
object currently owns the keyboard focus - orfalse
otherwisefocusedElement ():DOMMaLi
returns a (possible empty)dommali
object representing the DOM element which currently owns the keyboard focus
transition (Settings:PlainObject, Options?:PlainObject):DOMMaLi
defines a CSS transition (as specified by the optionalOptions
) for all CSS properties given by the keys ofSettings
and all HTML elements represented by thisdommali
object and starts this transition by setting every CSS property to the value given inSettings
. Options may customize the transition with aduration
(in ms), an initialdelay
(in ms) and/or aneasing
function. Additionally, acleanup
option may be defined which, iftrue
, restores the transition settings at the end of a transition to their values before invoking this method
dommali
contains additional support for simplified and streamlined event handling.
Nota bene:
waitFor
andrepeatUntil
were inspired by _hyperscript
Both event handler management functions and waitFor
or repeatUntil
support "anchored events", i.e., event names followed by a CSS selector which restricts the events to be handled to those triggered on specific elements only. JQuery (and its look-alikes) support this declaration of "delegated event handlers" by means of an additional "selector" argument to functions like on
, once
or off
- dommali
additionally allows event name and event target selector to be specified within a single string argument just by separating them with an "at"-character @
:
"event-name@selector"
For this to become possible, however, in dommali
the syntax of event names has been narrowed a bit: while HTML actually allows event names in almost any format (including spaces and control characters), dommali
defines the following syntax rules:
Event names
- have to start with a roman letter (a-z), a dollar sign or an underscore, optionally followed by one or multiple decimal digits (0-9), roman letters (a-z), dollar signs or underscores
- optionally followed by one or multiple groups of a single hyphen, dot or colon followed by one or multiple decimal digits (0-9), roman letters (a-z), dollar signs or underscores
The corresponding JavaScript RegExp is /^[a-z$_][a-z$_0-9]*([-.:][a-z$_0-9]+)*@.*$/
In an "anchored event" specification, this event name is followed by an "at" sign and one or multiple CSS selectors. The special "selector" this
restricts incoming events to those triggered at the listening element itself. Typical examples look like:
[email protected]
orpointermove@this
waitFor (...anchoredEventsOrTimeout:(string|number)[])
returns a promise which resolves as soon as one of the given anchoredEvents
has been received or the number of milliseconds given by a Timeout
have passed.
waitFor
has to be invoked as a method on a dommali
object as it dynamically registers and unregisters event handlers on its DOM elements.
In an asynchronous function, waitFor
is a simple approach to wait for the arrival of an event (as shown in the following example):
const $ = dommali // make "dommali" calls look like "jQuery" ones
$(document.body).waitFor('mousedown','pointerdown',5000).then((Result) => {
switch (true) {
case typeof Result === 'number': ... (handle timeout)
case Result.type === 'mousedown': ... (handle 'mousedown')
default: ... (handle 'pointerdown')
}
})
repeatUntil (...anchoredEventsOrTimeoutOrLoopBody:(string|number|Function)[])
returns a promise which resolves after one of the given anchoredEvents
has been received or the number of milliseconds given by a Timeout
have passed. Until then, the given (asynchronous) LoopBody
function will be executed as often as possible. If LoopBody
returns any other value but undefined
, the loop is terminated and the promise resolves to the loop body's return value. After receiving an event, repeatUntil
resolves to that event as soon as LoopBody
has finished without any return value; in case of a timeout it resolves to the actual number of milliseconds that have passed since the initial invocation - but again, only after LoopBody
has finished without any return value.
repeatUntil
has to be invoked as a method on a dommali
object as it dynamically registers and unregisters event handlers on its DOM elements.
In an asynchronous function, repeatUntil
may be used to simplify the proper handling of multiple consecutively arriving events. For example, the following code snippet makes all DOM elements with CSS class draggable
draggable within their parent:
const $ = dommali // make "dommali" calls look like "jQuery" ones
$(document.body).on('[email protected]',async function (Event) { // invocation-specific "this"
if (Event.button !== 0) { return }
let $Draggable = $(Event.target)
let $Container = $Draggable.parent()
let OffsetX = Event.offsetX + $Container.positionOnPage().left
let OffsetY = Event.offsetY + $Container.positionOnPage().top
let PointerId = Event.pointerId
this.subject(0).setPointerCapture(PointerId)
let Result = await this.repeatUntil('pointerup', 5000, async () => { // closure "this"
Event = await this.waitFor('pointermove','pointerup')
if (Event.type === 'pointermove') {
$Draggable.css({ left:(Event.pageX-OffsetX)+'px', top:(Event.pageY-OffsetY)+'px' })
}
})
this.subject(0).releasePointerCapture(PointerId)
})
(please note the use of both function
and "fat-arrow" literals because of the desired this
handling)
You may easily build this package yourself.
Just install NPM according to the instructions for your platform and follow these steps:
- either clone this repository using git or download a ZIP archive with its contents to your disk and unpack it there
- open a shell and navigate to the root directory of this repository
- run
npm install
in order to install the complete build environment - execute
npm run build
to create a new build
You may also look into the author's build-configuration-study for a general description of his build environment.