Standard library · Web and services

dom

Working with a web page in the browser: elements, events, timers and JavaScript objects.

import dom

This package lets a Salam program drive a web page: find and create elements, change their text, classes and styles, react to clicks and keys, run timers and keep small values in localStorage. A program that uses it runs in the browser. Translate it to JavaScript with salam build app.salam --platform=js --output=app.js and load it with a <script src="app.js"> tag; main runs once the page is ready, and println writes to the browser console. That is why the examples on this page are only checked, not run. For drawing use web.canvas, for games that read the keyboard every frame web.keys, and for a desktop window around a page webview.

Elements and other JavaScript objects are held in an i64 variable, and events and timers take an anonymous function such as (): ... end. Each function maps to one browser call (SetText is textContent, SetStyle is style.setProperty and so on), so the MDN documentation for that call applies.

Things that catch people out:

•

A missing element is JavaScript null, not 0. el == 0 is never true for it, and using it throws. Check with Exists(id) before ById, or with CountOf(QueryAll(sel)) == 0 for a selector.

•

SetHtml runs whatever HTML it gets. Put text from users in with SetText, never with SetHtml.

•

SetStyle takes CSS names such as background-color, not the JavaScript form backgroundColor.

•

OnReady does nothing when called from main, because main already runs after the page is ready and the browser does not repeat the ready event. Put start-up code straight in main.

•

OffEvent needs the very function value you registered, so keep it in a variable; a second lambda with the same body is a different function.

Running the examples

Each program below is a whole page's script. Save it as app.salam, translate it, and open an HTML file that loads the result:

salam build app.salam --platform=js --output=app.js
echo '<!doctype html><meta charset="utf-8"><body><script src="app.js"></script>' > index.html
salam serve .

Then visit http://127.0.0.1:8000. Output from println appears in the browser console. With --output=app.html instead, salam build --platform=js writes one self contained page.

A to-do list

Most pages follow the same shape: build the elements once in main, keep the ones you need later in global variables, and react to events. A click handler that is created inside a function, like the one on each new list item, remembers the element it was made for. StoreSetInt and StoreGetInt keep a number in the browser's localStorage, so it survives a reload.

dom-todo.salam
import dom

mut list := 0 as i64
mut entry := 0 as i64
mut added := 0

func add_item(text: str):
    item := dom.Create("li")
    dom.SetText(item, text)
    dom.OnEvent(item, "click", (): dom.ToggleClass(item, "done") end)
    dom.Append(list, item)
    added++
    dom.StoreSetInt("todo-added", added as i64)
end

func main:
    dom.SetTitle("To do")
    entry = dom.Create("input")
    dom.SetAttr(entry, "placeholder", "What needs doing?")
    button := dom.Create("button")
    dom.SetText(button, "Add")
    list = dom.Create("ul")
    dom.Append(dom.Body(), entry)
    dom.Append(dom.Body(), button)
    dom.Append(dom.Body(), list)

    dom.OnEvent(button, "click", (): text := dom.GetValue(entry) if text.Len() > 0: add_item(text) dom.SetValue(entry, "") end end)
    dom.OnEventE(entry, "keydown", (e: i64): if dom.EventKey(e) == "Enter": dom.PreventDefault(e) text := dom.GetValue(entry) if text.Len() > 0: add_item(text) dom.SetValue(entry, "") end end end)
    println "items added on this device so far:", dom.StoreGetInt("todo-added")
end

OnEvent takes a handler without arguments; use OnEventE when you need the event itself, for example to read the key with EventKey or to stop the browser's default action with PreventDefault.

Working with elements already on the page

When the HTML comes from a server or a template, the script finds the elements instead of creating them. This one filters a product table as the user types. It first checks with Exists that the page has what it needs, then takes every row with QueryAll and walks them with CountOf and ItemAt. Hiding a row is SetStyle(row, "display", "none"), and an empty value removes the style again.

dom-filter.salam
import dom
import str

func filter(rows: i64, word: str, counter: i64):
    mut shown := 0
    repeat dom.CountOf(rows) in i:
        row := dom.ItemAt(rows, i)
        name := str.Lower(dom.GetText(row))
        if word.Len() == 0 or str.Contains(name, word):
            dom.SetStyle(row, "display", "")
            shown++
        else:
            dom.SetStyle(row, "display", "none")
        end
    end
    dom.SetText(counter, shown + " of " + dom.CountOf(rows) + " products")
end

func main:
    if not (dom.Exists("search") and dom.Exists("count")):
        println "this script needs #search and #count on the page"
        ret
    end
    search := dom.ById("search")
    counter := dom.ById("count")
    rows := dom.QueryAll("#products tr")
    if dom.CountOf(rows) == 0:
        dom.SetText(counter, "no products")
        ret
    end
    dom.SetStyle(dom.Query("#products"), "background-color", "#fafafa")
    dom.OnEvent(search, "input", (): filter(rows, str.Lower(str.Trim(dom.GetValue(search))), counter) end)
    filter(rows, "", counter)
end

It expects markup such as <input id="search"> <p id="count"></p> <table id="products"><tr><td>Green tea</td></tr>...</table>. QueryAll returns the rows that exist at that moment; rows added later are not in the list, so query again after you change the table.

Checking a form as the user types

The input event fires on every change to a text box, which makes it the place for live checks. One function looks at all fields, writes the first problem into a message element and switches the button with SetBool(el, "disabled", ...). Calling it once at the end of main puts the form in the right state before the user touches it.

dom-form-check.salam
import dom
import str

mut email := 0 as i64
mut password := 0 as i64
mut submit := 0 as i64
mut note := 0 as i64

func check():
    e := dom.GetValue(email)
    p := dom.GetValue(password)
    mut problem := ""
    if not str.Contains(e, "@"):
        problem = "Enter an email address."
    else p.Len() < 8:
        problem = "The password needs at least 8 characters."
    end
    dom.SetText(note, problem)
    dom.SetBool(submit, "disabled", problem.Len() > 0)
    if problem.Len() > 0:
        dom.AddClass(note, "error")
    else:
        dom.RemoveClass(note, "error")
    end
end

func main:
    email = dom.Create("input")
    dom.SetAttr(email, "type", "email")
    password = dom.Create("input")
    dom.SetAttr(password, "type", "password")
    submit = dom.Create("button")
    dom.SetText(submit, "Sign up")
    note = dom.Create("p")
    each el in [email, password, submit, note]:
        dom.Append(dom.Body(), el)
    end
    dom.OnEvent(email, "input", (): check() end)
    dom.OnEvent(password, "input", (): check() end)
    dom.OnEvent(submit, "click", (): dom.Alert("Welcome, " + dom.GetValue(email)) end)
    check()
end

An event wants a function value, so wrap a named function in a short lambda: (): check() end. Checks in the browser are for the user's comfort only; the server must check the same things again, for example with net.http.validate.

A countdown with a timer

SetInterval calls a function every so many milliseconds and returns an id; keep it in a global so the function can stop itself with ClearInterval. For a single delayed call use SetTimeout, and for anything that moves on screen use EveryFrame instead, which follows the display's refresh rate.

dom-countdown.salam
import dom

mut left := 10
mut timer := 0 as i64
mut label := 0 as i64

func main:
    label = dom.Create("h1")
    dom.Append(dom.Body(), label)
    dom.SetText(label, "" + left)
    timer = dom.SetInterval((): left-- dom.SetText(label, "" + left) if left == 0: dom.ClearInterval(timer) dom.SetText(label, "Time is up") dom.SetStyle(label, "color", "crimson") dom.Tone(660, 300) end end, 1000)
end

Tone plays a short beep through the Web Audio API. Browsers only allow sound after the user has clicked or typed something on the page, so a beep from a timer that started on load may stay silent.

Functions

Query

#
func Query(sel: str): i64

The first element that matches the CSS selector; JavaScript null when there is none, which does not compare equal to 0.

dom-Elements.salam
import dom

func main:
    list := dom.Create("ul")
    dom.SetAttr(list, "id", "books")
    dom.Append(dom.Body(), list)
    repeat 3 in i:
        item := dom.Create("li")
        dom.SetText(item, "book " + (i + 1))
        dom.AddClass(item, "book")
        dom.Append(list, item)
    end
    println dom.Exists("books"), dom.Exists("nothing")

    all := dom.QueryAll("li.book")
    println dom.CountOf(all)
    second := dom.ItemAt(all, 1)
    println dom.GetText(second)
    dom.ToggleClass(second, "selected")
    println dom.GetAttr(second, "class")
    dom.RemoveClass(second, "book")
    println dom.GetAttr(second, "class")

    dom.SetStyle(second, "color", "red")
    println dom.GetStyle(second, "color")
    first := dom.Query("li")
    dom.Remove(first)
    println dom.CountOf(dom.QueryAll("li"))

    box := dom.ById("books")
    dom.SetHtml(box, "<li>new</li>")
end

QueryAll

#
func QueryAll(sel: str): i64

Every element that matches the selector, as a list; read it with CountOf and ItemAt.

The example for this item is shown with the ones above: dom-Elements.salam

ById

#
func ById(id: str): i64

The element with this id; null when there is none, so check with Exists first.

The example for this item is shown with the ones above: dom-Elements.salam

Exists

#
func Exists(id: str): bool

An element with this id is there.

The example for this item is shown with the ones above: dom-Elements.salam

Create

#
func Create(tag: str): i64

A new element with this tag; it is not in the page until you Append it.

The example for this item is shown with the ones above: dom-Elements.salam

Body

#
func Body(): i64

The body element of the page.

The example for this item is shown with the ones above: dom-Elements.salam

Document

#
func Document(): i64

The document object.

dom-Objects.salam
import dom

func main:
    d := dom.Document()
    println dom.GetStr(d, "title")
    dom.SetStr(d, "title", "my page")
    println dom.GetStr(d, "title")
    w := dom.Window()
    println dom.GetNum(w, "innerWidth") == dom.WinWidth()
    println dom.DocWidth() > 0, dom.DocHeight() > 0

    box := dom.Create("input")
    dom.SetBool(box, "disabled", true)
    println dom.GetBool(box, "disabled")
    dom.SetNum(box, "tabIndex", 3)
    println dom.GetNum(box, "tabIndex")
    dom.SetProp(box, "parentRef", dom.Body())
    println dom.GetProp(box, "parentRef") == dom.Body()

    math := dom.Global("Math")
    println dom.Call1(math, "abs", -5), dom.Call2(math, "max", 2, 9)
    println dom.Call3(math, "max", 1, 2, 3), dom.Call4(math, "min", 4, 3, 2, 1)
    _ := dom.Call0(box, "focus")
    _ := dom.CallS1(box, "removeAttribute", "placeholder")
    _ := dom.CallS2(box, "setAttribute", "name", "q")
    println dom.GetAttr(box, "name")

    canvas := dom.Create("canvas")
    ctx := dom.GetContext(canvas, "2d")
    println ctx != 0

    dom.StoreSetInt("best", 42)
    dom.StoreSetStr("name", "Maryam")
    println dom.StoreGetInt("best"), dom.StoreGetStr("name")

    r := dom.Random()
    println r >= 0.0 and r < 1.0, dom.RandomInt(6) < 6
    println dom.Now() >= 0.0

    button := dom.Create("button")
    greet := ():
        println "hello"
    end
    dom.OnEvent(button, "click", greet)
    dom.OffEvent(button, "click", greet)

    image := dom.LoadImage("logo.png")
    println dom.ImageReady(image)
    dom.Tone(440, 200)
    if dom.Confirm("shall we go on?"):
        name := dom.Prompt("what is your name?")
        dom.Alert("hello " + name)
    end
end

Window

#
func Window(): i64

The window object.

The example for this item is shown with the ones above: dom-Objects.salam

Global

#
func Global(name: str): i64

A global JavaScript object by name, such as Math.

The example for this item is shown with the ones above: dom-Objects.salam

Append

#
func Append(parent: i64, child: i64)

Adds the element to the end of the children of another element.

The example for this item is shown with the ones above: dom-Elements.salam

Remove

#
func Remove(el: i64)

Takes the element out of the page.

The example for this item is shown with the ones above: dom-Elements.salam

SetText

#
func SetText(el: i64, text: str)

Sets the text of the element; HTML in it is not interpreted.

The example for this item is shown with the ones above: dom-Elements.salam

GetText

#
func GetText(el: i64): str

The text of the element.

The example for this item is shown with the ones above: dom-Elements.salam

SetHtml

#
func SetHtml(el: i64, html: str)

Sets the HTML inside the element. Do not put text a user wrote in here.

The example for this item is shown with the ones above: dom-Elements.salam

SetValue

#
func SetValue(el: i64, value: str)

The value of an input box.

dom-Events.salam
import dom

mut count := 0

func main:
    button := dom.Create("button")
    dom.SetText(button, "click me")
    dom.SetAttr(button, "data-autofire", "click")
    dom.Append(dom.Body(), button)
    dom.OnEvent(button, "click", (): count++ println "click", count end)

    box := dom.Create("input")
    dom.SetAttr(box, "data-autofire", "keydown")
    dom.Append(dom.Body(), box)
    dom.SetValue(box, "hello")
    println dom.GetValue(box)
    dom.OnEventE(box, "keydown", (e: i64): if dom.EventKey(e) == "Enter": dom.PreventDefault(e) end dom.StopPropagation(e) println "target:", dom.GetValue(dom.EventTarget(e)) end)

    dom.OnWindowE("mousemove", (e: i64): println dom.EventX(e), dom.EventY(e) end)
    dom.OnWindowE("touchstart", (e: i64): println dom.TouchX(e), dom.TouchY(e) end)
    dom.OnWindow("scroll", (): println dom.ScrollX(), dom.ScrollY() end)
    dom.OnReady((): println "the page is ready" end)
    dom.OnResize((): println dom.WinWidth(), dom.WinHeight() end)
end

GetValue

#
func GetValue(el: i64): str

The current value of an input box.

The example for this item is shown with the ones above: dom-Events.salam

SetStyle

#
func SetStyle(el: i64, prop: str, value: str)

Sets one CSS property by its CSS name, such as color or background-color; an empty value removes it.

The example for this item is shown with the ones above: dom-Elements.salam

GetStyle

#
func GetStyle(el: i64, prop: str): str

The value of a CSS property set on the element itself.

The example for this item is shown with the ones above: dom-Elements.salam

SetAttr

#
func SetAttr(el: i64, name: str, value: str)

Sets one HTML attribute.

The example for this item is shown with the ones above: dom-Elements.salam

GetAttr

#
func GetAttr(el: i64, name: str): str

The value of an attribute; an empty string when there is none.

The example for this item is shown with the ones above: dom-Elements.salam

AddClass

#
func AddClass(el: i64, name: str)

Adds a class to the element.

The example for this item is shown with the ones above: dom-Elements.salam

RemoveClass

#
func RemoveClass(el: i64, name: str)

Takes a class away.

The example for this item is shown with the ones above: dom-Elements.salam

ToggleClass

#
func ToggleClass(el: i64, name: str)

Takes the class away when it is there, adds it when it is not.

The example for this item is shown with the ones above: dom-Elements.salam

OnEvent

#
func OnEvent(el: i64, event: str, handler: func())

Registers a function for an element event, such as click.

The example for this item is shown with the ones above: dom-Events.salam

OnEventE

#
func OnEventE(el: i64, event: str, handler: func(i64))

The same, but the function also takes the event object, to read with EventKey and the like.

The example for this item is shown with the ones above: dom-Events.salam

OnWindowE

#
func OnWindowE(event: str, handler: func(i64))

A function with the event object, for window events such as keydown.

The example for this item is shown with the ones above: dom-Events.salam

OffEvent

#
func OffEvent(el: i64, event: str, handler: func())

Drops a function that was registered before; you have to pass the same function, so keep it in a variable.

The example for this item is shown with the ones above: dom-Objects.salam

OnWindow

#
func OnWindow(event: str, handler: func())

A function for a window event, such as scroll.

The example for this item is shown with the ones above: dom-Events.salam

OnReady

#
func OnReady(handler: func())

Calls the function on the browser's DOMContentLoaded event. That event has already happened when main runs, so a call from main never fires.

The example for this item is shown with the ones above: dom-Events.salam

OnResize

#
func OnResize(handler: func())

Calls the function on every window resize.

The example for this item is shown with the ones above: dom-Events.salam

RequestFrame

#
func RequestFrame(handler: func(f64))

Calls the function once before the next frame is drawn; the function takes the time in milliseconds.

dom-Timers.salam
import dom

mut tick := 0
mut every := 0 as i64

func main:
    dom.SetTitle("timers")
    start := dom.Now()
    _ := dom.SetTimeout((): println "one second has passed" end, 1000)
    cancelled := dom.SetTimeout((): println "this never runs" end, 5000)
    dom.ClearTimeout(cancelled)
    every = dom.SetInterval((): tick++ if tick == 3: dom.ClearInterval(every) end end, 200)
    dom.RequestFrame((now: f64): println "frame after", now - start end)
    dom.EveryFrame((now: f64): _ := now end)
end

SetTimeout

#
func SetTimeout(handler: func(), ms: i64): i64

Calls the function once after this many milliseconds and returns an id.

The example for this item is shown with the ones above: dom-Timers.salam

SetInterval

#
func SetInterval(handler: func(), ms: i64): i64

Calls the function every this many milliseconds.

The example for this item is shown with the ones above: dom-Timers.salam

ClearTimeout

#
func ClearTimeout(id: i64)

Cancels a timeout that has not fired yet.

The example for this item is shown with the ones above: dom-Timers.salam

ClearInterval

#
func ClearInterval(id: i64)

Stops a repeat.

The example for this item is shown with the ones above: dom-Timers.salam

WinWidth

#
func WinWidth(): f64

The window width in pixels.

The example for this item is shown with the ones above: dom-Events.salam

WinHeight

#
func WinHeight(): f64

The window height.

The example for this item is shown with the ones above: dom-Events.salam

DocWidth

#
func DocWidth(): f64

The document width.

The example for this item is shown with the ones above: dom-Objects.salam

DocHeight

#
func DocHeight(): f64

The document height.

The example for this item is shown with the ones above: dom-Objects.salam

ScrollX

#
func ScrollX(): f64

The horizontal scroll position.

The example for this item is shown with the ones above: dom-Events.salam

ScrollY

#
func ScrollY(): f64

The vertical scroll position.

The example for this item is shown with the ones above: dom-Events.salam

Now

#
func Now(): f64

The exact time since the page loaded, in milliseconds; for measuring intervals.

The example for this item is shown with the ones above: dom-Timers.salam

GetProp

#
func GetProp(obj: i64, name: str): i64

A property of an object that is itself an object.

The example for this item is shown with the ones above: dom-Objects.salam

GetNum

#
func GetNum(obj: i64, name: str): f64

A numeric property; 0 when it is missing or not a number.

The example for this item is shown with the ones above: dom-Objects.salam

GetStr

#
func GetStr(obj: i64, name: str): str

A string property.

The example for this item is shown with the ones above: dom-Objects.salam

GetBool

#
func GetBool(obj: i64, name: str): bool

A boolean property.

The example for this item is shown with the ones above: dom-Objects.salam

SetProp

#
func SetProp(obj: i64, name: str, value: i64)

Sets a property on an object.

The example for this item is shown with the ones above: dom-Objects.salam

SetNum

#
func SetNum(obj: i64, name: str, value: f64)

Sets a numeric property.

The example for this item is shown with the ones above: dom-Objects.salam

SetStr

#
func SetStr(obj: i64, name: str, value: str)

Sets a string property.

The example for this item is shown with the ones above: dom-Objects.salam

SetBool

#
func SetBool(obj: i64, name: str, value: bool)

Sets a boolean property.

The example for this item is shown with the ones above: dom-Objects.salam

Call0

#
func Call0(obj: i64, method: str): i64

Calls a method of an object with no arguments and returns the result.

The example for this item is shown with the ones above: dom-Objects.salam

Call1

#
func Call1(obj: i64, method: str, a: f64): i64

With one numeric argument.

The example for this item is shown with the ones above: dom-Objects.salam

Call2

#
func Call2(obj: i64, method: str, a: f64, b: f64): i64

With two numeric arguments.

The example for this item is shown with the ones above: dom-Objects.salam

Call3

#
func Call3(obj: i64, method: str, a: f64, b: f64, c: f64): i64

With three numeric arguments.

The example for this item is shown with the ones above: dom-Objects.salam

Call4

#
func Call4(obj: i64, method: str, a: f64, b: f64, c: f64, d: f64): i64

With four numeric arguments.

The example for this item is shown with the ones above: dom-Objects.salam

CallS1

#
func CallS1(obj: i64, method: str, a: str): i64

With one string argument.

The example for this item is shown with the ones above: dom-Objects.salam

CallS2

#
func CallS2(obj: i64, method: str, a: str, b: str): i64

With two string arguments.

The example for this item is shown with the ones above: dom-Objects.salam

GetContext

#
func GetContext(canvas: i64, kind: str): i64

The drawing context of a canvas element, such as 2d; for easier drawing see web.canvas.

The example for this item is shown with the ones above: dom-Objects.salam

ItemAt

#
func ItemAt(listobj: i64, idx: i64): i64

One element of the list that QueryAll returned.

The example for this item is shown with the ones above: dom-Elements.salam

CountOf

#
func CountOf(listobj: i64): i64

The number of elements in the list.

The example for this item is shown with the ones above: dom-Elements.salam

EventTarget

#
func EventTarget(ev: i64): i64

The element the event happened on.

The example for this item is shown with the ones above: dom-Events.salam

EventX

#
func EventX(ev: i64): f64

The horizontal position of the mouse pointer in the event, from the left edge of the window (clientX).

The example for this item is shown with the ones above: dom-Events.salam

EventY

#
func EventY(ev: i64): f64

The vertical position of the pointer.

The example for this item is shown with the ones above: dom-Events.salam

EventKey

#
func EventKey(ev: i64): str

The key that was pressed, such as Enter or a.

The example for this item is shown with the ones above: dom-Events.salam

PreventDefault

#
func PreventDefault(ev: i64)

Stops the default action of the browser, such as submitting a form.

The example for this item is shown with the ones above: dom-Events.salam

StopPropagation

#
func StopPropagation(ev: i64)

Keeps the event from reaching the elements above.

The example for this item is shown with the ones above: dom-Events.salam

Alert

#
func Alert(msg: str)

Shows a message in a browser window.

The example for this item is shown with the ones above: dom-Objects.salam

Confirm

#
func Confirm(msg: str): bool

A question with an OK and a cancel button; true when the user confirmed.

The example for this item is shown with the ones above: dom-Objects.salam

Prompt

#
func Prompt(msg: str): str

Asks the user for some text; an empty string when they cancelled.

The example for this item is shown with the ones above: dom-Objects.salam

SetTitle

#
func SetTitle(title: str)

Sets the title of the browser tab.

The example for this item is shown with the ones above: dom-Timers.salam

EveryFrame

#
func EveryFrame(handler: func(f64))

Calls the function on every frame, for a game loop and animation. Its argument is the time since the previous frame in milliseconds, at most 100.

The example for this item is shown with the ones above: dom-Timers.salam

Random

#
func Random(): f64

A random number from 0 up to but not including 1.

The example for this item is shown with the ones above: dom-Objects.salam

RandomInt

#
func RandomInt(n: i64): i64

A random integer from 0 up to but not including n.

The example for this item is shown with the ones above: dom-Objects.salam

Tone

#
func Tone(freq: f64, ms: f64)

Plays a plain beep at the given frequency and length; browsers only allow sound after a click or a key.

The example for this item is shown with the ones above: dom-Objects.salam

LoadImage

#
func LoadImage(src: str): i64

Starts loading an image and returns its object.

The example for this item is shown with the ones above: dom-Objects.salam

ImageReady

#
func ImageReady(img: i64): bool

The image has finished loading.

The example for this item is shown with the ones above: dom-Objects.salam

StoreGetInt

#
func StoreGetInt(key: str): i64

A number kept in browser storage (localStorage); zero when there is none.

The example for this item is shown with the ones above: dom-Objects.salam

StoreSetInt

#
func StoreSetInt(key: str, v: i64)

Puts a number in browser storage; it stays after the page is closed.

The example for this item is shown with the ones above: dom-Objects.salam

StoreGetStr

#
func StoreGetStr(key: str): str

The stored text.

The example for this item is shown with the ones above: dom-Objects.salam

StoreSetStr

#
func StoreSetStr(key: str, v: str)

Stores some text.

The example for this item is shown with the ones above: dom-Objects.salam

TouchX

#
func TouchX(ev: i64): f64

The horizontal position of the first finger in a touch event.

The example for this item is shown with the ones above: dom-Events.salam

TouchY

#
func TouchY(ev: i64): f64

The vertical position of the first finger.

The example for this item is shown with the ones above: dom-Events.salam