Js.Dom
Dom — browser DOM bindings for March compiled with --target js.
Provides typed wrappers over the browser's Document Object Model. Each function is a thin call onto the matching DOM API (named in its doc), so browser semantics apply, including the browser's exceptions: an invalid CSS selector or tag name, or removing a node from the wrong parent, throws a JS exception rather than returning an error value. Lookups that can come up empty return Option; lists of nodes come back in document order. Requires --target js; the native compiler and REPL have no implementation of these externs.
Usage: match Js.Dom.find("counter") do None -> () Some(el) -> Js.Dom.set_text(el, "0") Js.Dom.listen(el, "click", fn _ -> Js.Dom.set_text(el, "clicked!")) end
Note: set_timeout/set_interval/on_frame take a zero-arg callback typed Unit -> Unit — pass a 0-arg lambda fn -> ... (the typechecker accepts fn -> body against a Unit -> Unit parameter, treating it as a unit-consuming thunk); a 1-arg fn _ -> ... is accepted too.
Functions
Add CSS class cls to el's classList. No-op if already present. cls must be a single class name: an empty string or one containing whitespace throws.
Show a browser alert() dialog with msg. Blocks the whole page, including timers and animation frames, until the user dismisses it.
Append child as the last child of parent (appendChild). If child is already in the tree it is moved, not copied.
The document's <body> element (document.body).
Return the direct element children of el (el.children) as a List(Node) in document order. Text and comment nodes are excluded; empty if there are none.
Remove all child nodes from el (elements and text alike, via replaceChildren()), leaving it empty.
Return a deep clone of el (cloneNode(true): attributes and all descendants), detached from the tree. Event listeners are not copied, and an id attribute is duplicated, so change it before inserting the clone.
Create a new element with the given HTML tag name (document.createElement), e.g. "div", "span", "button". The element is detached until appended or prepended into the tree. A string that is not a valid tag name throws.
Examples
let btn = Js.Dom.create("button")
Js.Dom.set_text(btn, "Start")
Js.Dom.add_class(btn, "primary")
Js.Dom.append(Js.Dom.body(), btn)Return the key of a `\
Return the element the event was dispatched to (event.target). For a listener on a container this is the innermost element that was clicked, not necessarily the element listen was called on.
Return the event type string for ev (event.type, e.g. \
Return the x-coordinate of a mouse/pointer event relative to the target element's padding edge (event.offsetX), truncated toward zero to an Int. Useful for hit-testing clicks on a <canvas>. Only meaningful for mouse and pointer events; on others (e.g. key events) the result is not a valid number.
Return the y-coordinate of a mouse/pointer event relative to the target element (event.offsetY), truncated toward zero; see event_x.
Look up an element by its id attribute (document.getElementById). Returns None if no element in the document has that id; detached elements are not found.
Return the first element child of el (firstElementChild), or None if el has no element children. Text nodes are skipped.
Return the value of the named attribute (getAttribute), or None if el does not have it. Present-but-empty attributes give Some("").
Examples
let score = match Js.Dom.get_attr(el, "data-score") do
Some(s) -> s
None -> "0"
endReturn the innerHTML of el: its children serialized as an HTML string.
Return the inline CSS value of prop on el (el.style.getPropertyValue, kebab-case names), or \
Return the textContent of el: the text of all its descendants concatenated, with no markup (hidden elements included). An element with no text gives \
Return the current value property of a form <input>, <textarea> or <select> (what the user typed or picked, not the value attribute). Returns \
Return true if el has the named attribute, even with an empty value (hasAttribute), false otherwise.
Return true if el's classList contains cls, false otherwise.
Return the current page URL (window.location.href), including any query string and fragment.
Drain and return the keys pressed since the last call (event.key strings of document-level keydown events, e.g. " ", "ArrowLeft", "a"), oldest first; a held key shows up repeatedly as the browser auto-repeats it. The first call installs the buffering listener and returns []. That listener prevents the browser default ONLY for space and arrow keys, so game input does not scroll the page. Poll once per animation frame.
Return the last element child of el (lastElementChild), or None if el has no element children. Text nodes are skipped.
Attach handler to el for DOM event event (addEventListener), e.g. "click", "input", "keydown", "pointerdown". The handler receives the Event; use event_target, event_key, event_x/event_y on it. Each call adds another listener (attaching the same handler twice runs it twice), and there is currently no way to detach one (see unlisten).
Examples
Js.Dom.listen(Js.Dom.body(), "keydown", fn ev ->
if Js.Dom.event_key(ev) == "Escape" do Js.Dom.prevent_default(ev) else () end)Schedule cb to run once before the next browser repaint (requestAnimationFrame), typically about 60 times a second; browsers pause it in background tabs. For a continuous animation loop, call on_frame again from inside cb. cb is a zero-arg callback; pass fn -> ....
Examples
fn frame() do
draw()
Js.Dom.on_frame(fn -> frame())
endReturn the parent element of el (parentElement), or None if el is the root <html> element, is detached, or its parent is not an element (e.g. a document fragment).
The live cursor position over el as element-relative (x, y) Ints, tracked by a mousemove listener installed on the first call. Until the mouse first moves over el it is el's center (as measured on that first call). Touch input does not update it; use taps. Unlike taps, this reads the current position rather than draining a buffer.
Insert child before all existing children of parent (prepend). If child is already in the tree it is moved, not copied.
Prevent the browser's default action for ev (preventDefault), e.g. stop a link from navigating, a form from submitting, or arrow keys from scrolling the page.
Detach el from its parent, removing it (and its subtree) from the DOM (el.remove()). No-op if el has no parent. The node stays usable and can be re-inserted.
Remove the named attribute from el (removeAttribute). No-op if the attribute is absent.
Remove child from parent (removeChild). Throws a NotFoundError DOM exception if child is not a direct child of parent; prefer remove when the parent is unknown.
Remove CSS class cls from el's classList. No-op if absent.
Find the first element in document order matching a CSS selector (document.querySelector), e.g. ".my-class", "h1", "[data-foo]" or "#board .cell". Returns None if nothing matches. An invalid selector throws.
Examples
match Js.Dom.select("#scoreboard .points") do
Some(el) -> Js.Dom.set_text(el, "0")
None -> ()
endFind every element matching a CSS selector (document.querySelectorAll), as a List(Node) in document order; empty when nothing matches. The list is a snapshot: later DOM changes do not update it. An invalid selector throws.
Examples
List.each(Js.Dom.select_all(".cell"), fn c -> Js.Dom.remove_class(c, "lit"))Set the named attribute on el to val (setAttribute), adding it or overwriting its old value, e.g. `set_attr(el, \
Set the innerHTML of el, replacing its children with the result of parsing html as HTML. Never pass untrusted text (it can inject markup); use set_text for plain text.
Call cb every ms milliseconds, forever (setInterval). Returns no handle, so it cannot be cancelled: to stop the work, have cb check a flag (e.g. a data-* attribute) and do nothing. For variable delays, re-arm a set_timeout from its own callback instead. cb is a zero-arg callback; pass fn -> ....
Set an inline CSS property on el (el.style.setProperty). prop uses the CSS (kebab-case) name, e.g. "background-color", not the JS camelCase one, which is silently ignored. Pass an empty string as val to remove the property; an invalid value is ignored and leaves the old one.
Examples
Js.Dom.set_style(el, "color", "red")
Js.Dom.set_style(el, "transform", "translateX(40px)")
Js.Dom.set_style(el, "background", "") -- remove it againSet the textContent of el, replacing all of its children with a single text node. The string is not interpreted as HTML, so this is the safe way to show untrusted text.
Call cb once after ms milliseconds (setTimeout). Non-blocking: it returns immediately and cb runs later on the event loop. Returns no handle, so a timeout cannot be cancelled. cb is a zero-arg callback; pass fn -> ....
Examples
Js.Dom.set_timeout(1500, fn -> Js.Dom.remove_class(banner, "visible"))Set the value property of a form <input>, <textarea> or <select>. This does not fire input/change events.
Stop ev from bubbling up to listeners on ancestor elements (stopPropagation). Other listeners on the same element still run.
Read key from the browser's localStorage (per-origin, persists across page loads). Returns None if the key is absent or storage is unavailable (e.g. blocked in private browsing).
Write val under key in the browser's localStorage, replacing any old value. Silently does nothing if storage is unavailable or full. Values are strings: encode numbers or records yourself.
Examples
Js.Dom.store_set("best", int_to_string(score))
let best = match Js.Dom.store_get("best") do
Some(s) -> s
None -> "0"
endDrain and return the pointer taps on el since the last call, oldest first, as element-relative (x, y) Int pairs. The first call installs a buffering pointerdown listener (mouse, touch and pen alike; mousedown/touchstart on engines without Pointer Events) and so returns []; call it once at startup. Each tap is delivered exactly once. Poll once per animation frame for game input.
Examples
List.each(Js.Dom.taps(canvas), fn tap -> handle_tap(tap)) -- tap : (Int, Int)Create a detached text node containing text (document.createTextNode); the string is never parsed as HTML. Attach it with append or prepend.
Toggle CSS class cls on el: add it if absent, remove it if present.
Intended to remove a listener attached with listen, but currently does nothing: listen registers a fresh JS wrapper function around handler, and this call removes another fresh wrapper that was never registered, so the original listener stays attached. To stop reacting to an event, have the handler check a flag (e.g. a data-* attribute) instead.
The browser window's inner size (window.innerWidth/innerHeight) in CSS pixels, as (w, h) Ints. No devicePixelRatio handling.