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 js app.salam --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 == 0is never true for it, and using it throws. Check withExists(id)beforeById, or withCountOf(QueryAll(sel)) == 0for a selector. SetHtmlruns whatever HTML it gets. Put text from users in withSetText, never withSetHtml.SetStyletakes CSS names such asbackground-color, not the JavaScript formbackgroundColor.OnReadydoes nothing when called frommain, becausemainalready runs after the page is ready and the browser does not repeat the ready event. Put start-up code straight inmain.OffEventneeds 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 js app.salam --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 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.
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")
endOnEvent 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.
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)
endIt 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.
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()
endAn 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.
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)
endTone 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): i64null when there is none, which does not compare equal to 0.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>")
endQueryAll
func QueryAll(sel: str): i64CountOf and ItemAt.The example for this item is shown with the ones above: dom-Elements.salam
ById
func ById(id: str): i64null 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): boolThe example for this item is shown with the ones above: dom-Elements.salam
Create
func Create(tag: str): i64Append it.The example for this item is shown with the ones above: dom-Elements.salam
Body
func Body(): i64body element of the page.The example for this item is shown with the ones above: dom-Elements.salam
Document
func Document(): i64document object.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
endWindow
func Window(): i64window object.The example for this item is shown with the ones above: dom-Objects.salam
Global
func Global(name: str): i64Math.The example for this item is shown with the ones above: dom-Objects.salam
Append
func Append(parent: i64, child: i64)The example for this item is shown with the ones above: dom-Elements.salam
Remove
func Remove(el: i64)The example for this item is shown with the ones above: dom-Elements.salam
SetText
func SetText(el: i64, text: str)The example for this item is shown with the ones above: dom-Elements.salam
GetText
func GetText(el: i64): strThe example for this item is shown with the ones above: dom-Elements.salam
SetHtml
func SetHtml(el: i64, html: str)The example for this item is shown with the ones above: dom-Elements.salam
SetValue
func SetValue(el: i64, value: str)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)
endGetValue
func GetValue(el: i64): strThe example for this item is shown with the ones above: dom-Events.salam
SetStyle
func SetStyle(el: i64, prop: str, value: str)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): strThe example for this item is shown with the ones above: dom-Elements.salam
SetAttr
func SetAttr(el: i64, name: str, value: str)The example for this item is shown with the ones above: dom-Elements.salam
GetAttr
func GetAttr(el: i64, name: str): strThe example for this item is shown with the ones above: dom-Elements.salam
AddClass
func AddClass(el: i64, name: str)The example for this item is shown with the ones above: dom-Elements.salam
RemoveClass
func RemoveClass(el: i64, name: str)The example for this item is shown with the ones above: dom-Elements.salam
ToggleClass
func ToggleClass(el: i64, name: str)The example for this item is shown with the ones above: dom-Elements.salam
OnEvent
func OnEvent(el: i64, event: str, handler: func())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))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))keydown.The example for this item is shown with the ones above: dom-Events.salam
OffEvent
func OffEvent(el: i64, event: str, handler: func())The example for this item is shown with the ones above: dom-Objects.salam
OnWindow
func OnWindow(event: str, handler: func())scroll.The example for this item is shown with the ones above: dom-Events.salam
OnReady
func OnReady(handler: func())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())The example for this item is shown with the ones above: dom-Events.salam
RequestFrame
func RequestFrame(handler: func(f64))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)
endSetTimeout
func SetTimeout(handler: func(), ms: i64): i64The example for this item is shown with the ones above: dom-Timers.salam
SetInterval
func SetInterval(handler: func(), ms: i64): i64The example for this item is shown with the ones above: dom-Timers.salam
ClearTimeout
func ClearTimeout(id: i64)The example for this item is shown with the ones above: dom-Timers.salam
ClearInterval
func ClearInterval(id: i64)The example for this item is shown with the ones above: dom-Timers.salam
WinWidth
func WinWidth(): f64The example for this item is shown with the ones above: dom-Events.salam
WinHeight
func WinHeight(): f64The example for this item is shown with the ones above: dom-Events.salam
DocWidth
func DocWidth(): f64The example for this item is shown with the ones above: dom-Objects.salam
DocHeight
func DocHeight(): f64The example for this item is shown with the ones above: dom-Objects.salam
ScrollX
func ScrollX(): f64The example for this item is shown with the ones above: dom-Events.salam
ScrollY
func ScrollY(): f64The example for this item is shown with the ones above: dom-Events.salam
Now
func Now(): f64The example for this item is shown with the ones above: dom-Timers.salam
GetProp
func GetProp(obj: i64, name: str): i64The example for this item is shown with the ones above: dom-Objects.salam
GetNum
func GetNum(obj: i64, name: str): f64The example for this item is shown with the ones above: dom-Objects.salam
GetStr
func GetStr(obj: i64, name: str): strThe example for this item is shown with the ones above: dom-Objects.salam
GetBool
func GetBool(obj: i64, name: str): boolThe example for this item is shown with the ones above: dom-Objects.salam
SetProp
func SetProp(obj: i64, name: str, value: i64)The example for this item is shown with the ones above: dom-Objects.salam
SetNum
func SetNum(obj: i64, name: str, value: f64)The example for this item is shown with the ones above: dom-Objects.salam
SetStr
func SetStr(obj: i64, name: str, value: str)The example for this item is shown with the ones above: dom-Objects.salam
SetBool
func SetBool(obj: i64, name: str, value: bool)The example for this item is shown with the ones above: dom-Objects.salam
Call0
func Call0(obj: i64, method: str): i64The example for this item is shown with the ones above: dom-Objects.salam
Call1
func Call1(obj: i64, method: str, a: f64): i64The example for this item is shown with the ones above: dom-Objects.salam
Call2
func Call2(obj: i64, method: str, a: f64, b: f64): i64The 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): i64The 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): i64The example for this item is shown with the ones above: dom-Objects.salam
CallS1
func CallS1(obj: i64, method: str, a: str): i64The example for this item is shown with the ones above: dom-Objects.salam
CallS2
func CallS2(obj: i64, method: str, a: str, b: str): i64The example for this item is shown with the ones above: dom-Objects.salam
GetContext
func GetContext(canvas: i64, kind: str): i642d; 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): i64QueryAll returned.The example for this item is shown with the ones above: dom-Elements.salam
CountOf
func CountOf(listobj: i64): i64The example for this item is shown with the ones above: dom-Elements.salam
EventTarget
func EventTarget(ev: i64): i64The example for this item is shown with the ones above: dom-Events.salam
EventX
func EventX(ev: i64): f64clientX).The example for this item is shown with the ones above: dom-Events.salam
EventY
func EventY(ev: i64): f64The example for this item is shown with the ones above: dom-Events.salam
EventKey
func EventKey(ev: i64): strEnter or a.The example for this item is shown with the ones above: dom-Events.salam
PreventDefault
func PreventDefault(ev: i64)The example for this item is shown with the ones above: dom-Events.salam
StopPropagation
func StopPropagation(ev: i64)The example for this item is shown with the ones above: dom-Events.salam
Alert
func Alert(msg: str)The example for this item is shown with the ones above: dom-Objects.salam
Confirm
func Confirm(msg: str): boolThe example for this item is shown with the ones above: dom-Objects.salam
Prompt
func Prompt(msg: str): strThe example for this item is shown with the ones above: dom-Objects.salam
SetTitle
func SetTitle(title: str)The example for this item is shown with the ones above: dom-Timers.salam
EveryFrame
func EveryFrame(handler: func(f64))The example for this item is shown with the ones above: dom-Timers.salam
Random
func Random(): f64The example for this item is shown with the ones above: dom-Objects.salam
RandomInt
func RandomInt(n: i64): i64The example for this item is shown with the ones above: dom-Objects.salam
Tone
func Tone(freq: f64, ms: f64)The example for this item is shown with the ones above: dom-Objects.salam
LoadImage
func LoadImage(src: str): i64The example for this item is shown with the ones above: dom-Objects.salam
ImageReady
func ImageReady(img: i64): boolThe example for this item is shown with the ones above: dom-Objects.salam
StoreGetInt
func StoreGetInt(key: str): i64The example for this item is shown with the ones above: dom-Objects.salam
StoreSetInt
func StoreSetInt(key: str, v: i64)The example for this item is shown with the ones above: dom-Objects.salam
StoreGetStr
func StoreGetStr(key: str): strThe example for this item is shown with the ones above: dom-Objects.salam
StoreSetStr
func StoreSetStr(key: str, v: str)The example for this item is shown with the ones above: dom-Objects.salam
TouchX
func TouchX(ev: i64): f64The example for this item is shown with the ones above: dom-Events.salam
TouchY
func TouchY(ev: i64): f64The example for this item is shown with the ones above: dom-Events.salam