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
thisto the DOM element just processed, instead they get a correspondingdommaliobject 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.,
positionInViewportvs.positionInParentvs.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
dommalidoes 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, supportextraParameterspassed when triggering an event and Eventdataspecified while registering an event handler- within asynchronous functions it is possible to
waitForthe arrival of an event or to write loops thatrepeatUntila 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"
@thiswhich effectively prevents the handler from being invoked by bubbling events - both event handler management functions and
waitFororrepeatUntilsupport 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 dommalidoes 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 emptydommaliobject, 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 adommaliobject representing all DOM elements matching the given CSS selectordommali(html:string):DOMMaLi
returns a newdommaliobject representing all DOM elements created from the given HTML codedommali(element:Element):DOMMaLi
returns a newdommaliobject representing the given DOM elementdommali(elements:Element[]):DOMMaLi
returns a newdommaliobject representing the given DOM elements (in the given order)dommali(bridge:DOMMaLi):DOMMaLi
returns a duplicate of the givendommaliobject
DOMMaLi.extraParametersOfEvent(Event:Event):any[]
returns the (possible empty) list of additional arguments passed when the givenEventwas 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 givendommaliobject, a given DOM element or in its own DOM element with given CSS settings. For that purpose, the optionalTemplateOrSettingsargument may contain either adommaliobject, 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-heightandwidth- other CSS settings will be ignored. Please note, that you may specify a desired textwidthexplicity 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 givendommaliobject, a given DOM element or in its own DOM element with given CSS settings. For that purpose, the optionalTemplateOrSettingsargument may contain either adommaliobject, 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-indentandtext-transform- other CSS settings will be ignored
get length ():number
contains the number of DOM elements represented by thisdommaliobjectsize ():number
returns the number of DOM elements represented by thisdommaliobjectisEmpty ():boolean
returnstrueif thisdommaliobject does not represent any DOM element - orfalseotherwisesubjects ():Element[]
returns a copy of the list of DOM elements represented by thisdommaliobjectsubject (Index:number):Element|undefined
returns the single item found at indexIndexin the list of DOM elements represented by thisdommaliobject - orundefinedif no such item existsindexOf (Value:Element|DOMMaLi):number
looks for the given DOM element or the first element represented by the givendommaliobject in the list of DOM elements represented by thisdommaliobject and returns its index - or-1if the element can not be found
slice (start?:number, end?:number):DOMMaLi
returns a newdommaliobject representing all items from the list of DOM elements represented by thisdommaliobject starting at indexstartand ending before indexend(or until the end of the list, ifendwas omitted). If bothstartandendare missing, thisdommaliobject is simply duplicatedfirst ():DOMMaLi
returns a newdommaliobject representing the first element from the list of DOM elements represented by thisdommaliobject - or any emptydommaliobject if this one is empty as welllast ():DOMMaLi
returns a newdommaliobject representing the last element from the list of DOM elements represented by thisdommaliobject - or any emptydommaliobject if this one is empty as welleq (Index:number):DOMMaLi
returns a newdommaliobject representing the element at indexIndexfrom the list of DOM elements represented by thisdommaliobject - or any emptydommaliobject if no such element exists
forEach (Callback:(Item:DOMMaLi, Index:number, Container:DOMMaLi) => any):DOMMaLi
iterates over all DOM elements represented by thisdommaliobject and invokes the givenCallbackfunction with the following arguments:
adommaliobject representing the current DOM element, its index in the list of DOM elements represented by thisdommaliobject and that object itself. In contrast to jQuery and many other similar libraries,thisis not bound to the current DOM element - this simplifies the use of "fat arrow" functions as callbacksfilter (Selector:string|String):DOMMaLi
returns a newdommaliobject representing only those DOM elements from thisdommaliobject which match the given CSS selectorfilter (Callback:(Item:DOMMaLi, Index:number, Container:DOMMaLi) => boolean):DOMMaLi
returns a newdommaliobject representing only those DOM elements from thisdommaliobject for which the givenCallbackfunction returns true. This function is invoked with the following arguments:
adommaliobject representing the current DOM element, its index in the list of DOM elements represented by thisdommaliobject and that object itself. In contrast to jQuery and many other similar libraries,thisis not bound to the current DOM element - this simplifies the use of "fat arrow" functions as callbacks
matches (Selector:string|String):boolean
returnstrueif the first DOM element represented by thisdommaliobject matches the given CSS selector - orfalseotherwisefind (Selector:string|String):DOMMaLi
returns a new (and possibly empty)dommaliobject representing all those DOM elements within the scope of thisdommaliobject that match the given CSS selectorfindFirst (Selector:string|String):DOMMaLi
returns a new (and possibly empty)dommaliobject representing the first DOM element within the scope of thisdommaliobject that matches the given CSS selector
positionInViewport ():{ left:number,top:number }|undefined
returns the rendering position of the first DOM element represented by thisdommaliobject relative to the current viewport (orundefinedif thisdommaliobject 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 thisdommaliobject relative to its "offset parent" (orundefinedif either thisdommaliobject 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 thisdommaliobject relative to the document (orundefinedif thisdommaliobject 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 nonewValueis given, this method returns the layout width of the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty or its first element is not an HTML element). Otherwise, the layout width of all HTML elements represented by thisdommaliobject is set to thenewValuepixelsheight (newValue?:number):number|DOMMaLi|undefined
if nonewValueis given, this method returns the layout height of the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty or its first element is not an HTML element). Otherwise, the layout height of all HTML elements represented by thisdommaliobject is set to thenewValuepixelslayoutWidth (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 thisdommaliobject (orundefinedif thisdommaliobject 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 thisdommaliobject (orundefinedif thisdommaliobject 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 thisdommaliobject (orundefinedif thisdommaliobject is empty) without border, padding and scrollbarsinnerHeight ():number|undefined
returns the "inner" layout height of the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty) without border, padding and scrollbars
parent ():DOMMaLi
returns a newdommaliobject representing the "parent" of the first DOM element represented by thisdommaliobject (or an emptydommaliobject if this one is empty as well)closest (Selector:string|String):DOMMaLi
returns a newdommaliobject representing the innermost element among the first DOM element represented by thisdommaliobject and its parents, that matches the givenSelector(or an emptydommaliobject if either this one is empty or no matching DOM element could be found)isAttached ():boolean
returnstrue, if the first DOM element represented by thisdommaliobject is part of the document - orfalseotherwisecontains (Candidate:DOMMaLi):boolean
returnstrue, if the first DOM element represented by thisdommaliobject contains the first DOM element represented by the givenCandidate- orfalseotherwisechildren (Selector?:string|String):DOMMaLi
ifSelectoris missing, this method returns a newdommaliobject representing all direct "children" of the first DOM element represented by thisdommaliobject. Otherwise, the newdommaliobject represents only those children which also match the given CSSSelectorfirstChild (Selector?:string|String):DOMMaLi
ifSelectoris missing, this method returns a newdommaliobject representing the first direct "child" of the first DOM element represented by thisdommaliobject. Otherwise, the newdommaliobject represents the first child which also matches the given CSSSelectorlastChild (Selector?:string|String):DOMMaLi
ifSelectoris missing, this method returns a newdommaliobject representing the last direct "child" of the first DOM element represented by thisdommaliobject. Otherwise, the newdommaliobject represents the last child which also matches the given CSSSelectorprev (Selector?:string|String):DOMMaLi
ifSelectoris missing, this method returns a newdommaliobject representing the immediately preceding "sibling" of the first DOM element represented by thisdommaliobject - i.e., the direct child of that element's parent, which immediately precedes it. Otherwise, the newdommaliobject represents the nearest preceding "sibling" which also matches the given CSSSelectornext (Selector?:string|String):DOMMaLi
ifSelectoris missing, this method returns a newdommaliobject representing the immediately following "sibling" of the first DOM element represented by thisdommaliobject - i.e., the direct child of that element's parent, which immediately follows it. Otherwise, the newdommaliobject represents the nearest following "sibling" which also matches the given CSSSelector
show ():DOMMaLi
makes all HTML elements represented by thisdommaliobject (potentially) visible by setting their CSS propertydisplayto a value different fromnone- if possible,dommalitries to restore any setting that was active before an element was hidden. Otherwise, it uses the default setting for the given element tag - orblockif all failshide ():DOMMaLi
makes all HTML elements represented by thisdommaliobject invisible by setting their CSS propertydisplaytonone
scrollLeft (newValue?:number):number|DOMMaLi|undefined
if nonewValueis given, this method returns the number of pixels by which the first DOM element represented by thisdommaliobject is scrolled from its left edge (orundefinedif thisdommaliobject is empty) Otherwise, it scrolls all DOM elements represented by thisdommaliobject to a positionnewValuepixels from their left edgescrollTop (newValue?:number):number|DOMMaLi|undefined
if nonewValueis given, this method returns the number of pixels by which the first DOM element represented by thisdommaliobject is scrolled from its top edge (orundefinedif thisdommaliobject is empty) Otherwise, it scrolls all DOM elements represented by thisdommaliobject to a positionnewValuepixels from their top edgescrollWidth ():number|undefined
returns the width of the contents of the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject 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 thisdommaliobject (orundefinedif thisdommaliobject 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 thisdommaliobject to a positionxpixels from their left andypixels from their top edge. If given,Modespecifies whether the scrolling should animate smoothly or happen instantly in a single jump
hasClass (Classes:string):boolean
returnstrueif the first DOM element represented by thisdommaliobject is associated with all (space-separated) CSS classes given byClasses- orfalseotherwiseaddClass (Classes:string):DOMMaLi
associates all DOM elements represented by thisdommaliobject with the (space-separated) CSS classes given byClassestoggleClass (Classes:string):DOMMaLi
toggles the association of all DOM elements represented by thisdommaliobject with the (space-separated) CSS classes given byClassesremoveClass (Classes:string):DOMMaLi
removes the association of all DOM elements represented by thisdommaliobject with the (space-separated) CSS classes given byClasses
append (Content:string|String|DOMMaLi|Element|Element[]):DOMMaLi
ifContentcontains HTML code, this method inserts the DOM elements repeatedly created based onContentat the end of every DOM element represented by thisdommaliobject - otherwise the DOM elements given byContentare inserted at the end of the first DOM element represented by thisdommaliobject only.Contentmay contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommaliobjectprepend (Content:string|String|DOMMaLi|Element|Element[]):DOMMaLi
ifContentcontains HTML code, this method inserts the DOM elements repeatedly created based onContentat the beginning of every DOM element represented by thisdommaliobject - otherwise the DOM elements given byContentare inserted at the beginning of the first DOM element represented by thisdommaliobject only.Contentmay contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommaliobjectinsertAfter (Content:DOMMaLi):DOMMaLi
inserts all DOM elements represented by thisdommaliobject after the first DOM element represented by the givenContent.Contentmay contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommaliobjectinsertBefore (Content:DOMMaLi):DOMMaLi
inserts all DOM elements represented by thisdommaliobject before the first DOM element represented by the givenContent.Contentmay contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommaliobjectreplaceWith (Replacement:string|String|DOMMaLi|Element|Element[]):void
ifContentcontains HTML code, this method replaces every DOM element represented by thisdommaliobject by the DOM elements repeatedly created based onContent- otherwise the first DOM element represented by thisdommaliobject is replaced by the DOM elements given byContent.Contentmay contain HTML code, CSS selectors, one or multiple DOM elements or anotherdommaliobjectremove ():DOMMaLi
removes all DOM elements represented by thisdommaliobject
prop (Property:string, newValue?:any):DOMMaLi|any|undefined
if nonewValueis given, this method returns the value of propertyPropertyof the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty). Otherwise, propertyPropertyof all DOM elements represented by thisdommaliobject is set tonewValuehasProp (Property:string):boolean
returnstrueif propertyPropertyis found in the first DOM element represented by thisdommaliobject - orfalseotherwiseremoveProp (Property:string):DOMMaLi
removes propertyPropertyfrom all DOM elements represented by thisdommaliobject
data (Key:string, newValue?:any):DOMMaLi|any|undefined
if nonewValueis given, this method returns the value of data entryKeyof the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty). Otherwise, data entryKeyof all DOM elements represented by thisdommaliobject 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
returnstrueif data entryKeyis found in the first DOM element represented by thisdommaliobject - orfalseotherwiseremoveData (Key:string):DOMMaLi
removes data entryKeyfrom all DOM elements represented by thisdommaliobject
attr (Attribute:string, newValue?:any):DOMMaLi|string|undefined
if nonewValueis given, this method returns the value of HTML attributeAttributeof the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty). Otherwise, the HTML attributeAttributeof all DOM elements represented by thisdommaliobject is set tonewValuehasAttr (Attribute:string):boolean
returnstrueif HTML attributeAttributeis found in the first DOM element represented by thisdommaliobject - orfalseotherwiseremoveAttr (Attribute:string):DOMMaLi
removes HTML attributeAttributefrom all DOM elements represented by thisdommaliobject
css (Property:string|string, newValue?:string):DOMMaLi|string|undefined
if nonewValueis given, this method returns the computed value of CSS propertyPropertyof the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty). Otherwise, the CSS propertyPropertyof all DOM elements represented by thisdommaliobject is set tonewValuecss (PropertyList:string[]):PlainObject|undefined
returns the computed values of all CSS properties given byPropertyListof the first DOM element represented by thisdommaliobject as a plain JavaScript object with the given property names as keys (orundefinedif thisdommaliobject is empty)css (PropertySet:PlainObject):DOMMaLi
sets the CSS properties given by the keys ofPropertySetof all DOM elements represented by thisdommaliobject to the values specified inPropertySet
html (newValue?:string):DOMMaLi|string|undefined
if nonewValueis given, this method returns the inner HTML of the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty). Otherwise, the inner HTML of all DOM elements represented by thisdommaliobject is set tonewValuetext (newValue?:string):DOMMaLi|string|undefined
if nonewValueis given, this method returns the inner text of the first DOM element represented by thisdommaliobject (orundefinedif thisdommaliobject is empty). Otherwise, the inner text of all DOM elements represented by thisdommaliobject is set tonewValueappendText (Value:string):DOMMaLi
inserts the text given byValueafter the inner text of all DOM elements represented by thisdommaliobjectprependText (Value:string):DOMMaLi
inserts the text given byValuebefore the inner text of all DOM elements represented by thisdommaliobject
on (anchoredEvent:string, Handler:Function):DOMMaLi
registers the given event handlerHandlerfor the eventanchoredEventin all DOM elements represented by thisdommaliobject.Handlerwill be invoked whenever the givenEventis 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). IfHandlerreturns the explicit valuefalse,Event.stopPropagation()andEvent.preventDefault()are called for the current eventon (Events:string, Handler:Function):DOMMaLi
registers the given event handlerHandlerfor every event in the (space-separated) list given byEventsin all DOM elements represented by thisdommaliobject.Handlerwill be invoked whenever one of the givenEventsis triggered on one of these DOM elements themselves or one of their descendants (if the event is allowed to "bubble"). IfHandlerreturns 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 handlerHandleras a "delegated event handler" for every event in the (space-separated) list given byEventsin all DOM elements represented by thisdommaliobject.Handlerwill be invoked whenever one of the givenEventsis 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. SettingSelectortonullsimply skips the matching. IfHandlerreturns the explicit valuefalse,Event.stopPropagation()andEvent.preventDefault()are called for the current eventon (anchoredEvent:string, Data:any, Handler:Function):DOMMaLi
registers the given event handlerHandlerfor the eventanchoredEventin all DOM elements represented by thisdommaliobject.Handlerwill be invoked whenever the givenEventis 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, propertydataof the incoming event is set toDatabefore the registered handler is called. IfHandlerreturns 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" ifSelectoris notnull) for every event in the (space-separated) list given byEventsin all DOM elements represented by thisdommaliobject.Handlerwill be invoked whenever one of the givenEventsis 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, propertydataof the incoming event is set toDatabefore the registered handler is called. SettingSelectortonullsimply skips the matching. IfHandlerreturns 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 givenHandlerupon its first invocationonce (anchoredEvent:string, Handler:Function):DOMMaLi
behaves likeonce(anchoredEvent,Handler), but automatically unregisters the givenHandlerupon its first invocationonce (Events:string, Selector:string|String|null, Handler:Function):DOMMaLi
behaves likeonce(Events,Selector,Handler), but automatically unregisters the givenHandlerupon its first invocationonce (anchoredEvent:string, Data:any, Handler:Function):DOMMaLi
behaves likeonce(anchoredEvent,Data,Handler), but automatically unregisters the givenHandlerupon its first invocationonce (Events:string, Selector:string|String|null, Data:any, Handler:Function):DOMMaLi
behaves likeonce(Events,Selector,Data,Handler), but automatically unregisters the givenHandlerupon its first invocation
off ():DOMMaLi
unregisters all event handlers registered in all DOM elements represented by thisdommaliobjectoff (anchoredEvent:string):DOMMaLi
unregisters all event handlers registered for the givenanchoredEventin all DOM elements represented by thisdommaliobjectoff (Events:string):DOMMaLi
unregisters all event handlers registered for every event in the (space-separated) list given byEventsin all DOM elements represented by thisdommaliobjectoff (Events:string, Selector:string|String|null):DOMMaLi
unregisters all event handlers registered as delegated event handlers with CSS selectorSelectorfor every event in the (space-separated) list given byEventsin all DOM elements represented by thisdommaliobjectoff (anchoredEvent:string, Handler:Function):DOMMaLi
unregisters the givenHandlerregistered for the givenanchoredEventin all DOM elements represented by thisdommaliobjectoff (Events:string, Selector:string|String|null, Handler:Function):DOMMaLi
unregisters the givenHandlerregistered as delegated event handler with CSS selectorSelectorfor every event in the (space-separated) list given byEventsin all DOM elements represented by thisdommaliobject
repeatUntil (...anchoredEventsOrTimeoutOrLoopBody:(string|number|Function)[]):Promise<any>
returns a promise which resolves after one of the givenanchoredEventshas been received or the number of milliseconds given by aTimeouthave passed. Until then, the given (asynchronous)LoopBodyfunction will be executed as often as possible. IfLoopBodyreturns any other value butundefined, the loop is terminated and the promise resolves to the loop body's return value. After receiving an event,repeatUntilresolves to that event as soon asLoopBodyhas 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 afterLoopBodyhas finished. All arguments exceptLoopBodyare optional - callingrepeatUntilsolely with aLoopBodysimply repeatedly executes that function until it returns a value different fromundefined(see Notes onrepeatUntil)trigger (Event:string|Event, extraParameters?:any[]):boolean
fires the givenEventon all DOM elements represented by thisdommaliobject. IfEventis given as a string, aCustomEventof typeEventis created and fired. The optional argumentextraParametersmay be a single value or a list of values which are passed as additional arguments (after the event object itself) to the Handler.triggerreturnsfalseif at least one of the invoked event handlers calledEvent.preventDefault()ortrueotherwisewaitFor (...anchoredEventsOrTimeout:(string|number)[]):Promise<any>
returns a promise which resolves as soon as one of the givenanchoredEventshas been received or the number of milliseconds given by aTimeouthave passed. All arguments are optional - callingwaitForwithout any arguments just resolves immediately. After receiving an event,waitForresolves 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 thisdommaliobject - provided that this is an HTML element and is allowed to be focused. Otherwise,focusdoes nothingblur ():DOMMaLi
removes the keyboard focus from the first DOM element represented by thisdommaliobject - provided that this is an HTML element and is currently focused. Otherwise,blurdoes nothinghasFocus ():boolean
returnstrue, if the first DOM element represented by thisdommaliobject currently owns the keyboard focus - orfalseotherwisefocusedElement ():DOMMaLi
returns a (possible empty)dommaliobject 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 ofSettingsand all HTML elements represented by thisdommaliobject 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 aneasingfunction. Additionally, acleanupoption 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:
waitForandrepeatUntilwere 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 installin order to install the complete build environment - execute
npm run buildto create a new build
You may also look into the author's build-configuration-study for a general description of his build environment.