js

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package js provides type-safe JavaScript string generation for HTML event attributes.

This package provides a builder API for generating JavaScript code strings suitable for use in HTML event handler attributes like onclick, onchange, etc. It integrates seamlessly with the github.com/jeffh/htmlgen/h package.

Quick Start

The most common use case is adding event handlers to HTML elements:

import (
    "github.com/jeffh/htmlgen/h"
    "github.com/jeffh/htmlgen/js"
)

// Simple click handler
button := h.Button(
    js.OnClick(js.ExprStmt(js.Alert(js.String("Hello!")))),
    h.Text("Say Hello"),
)
// Output: <button onclick="alert(&quot;Hello!&quot;)">Say Hello</button>

Type System

The package uses three core interfaces to ensure type safety:

  • Expr - JavaScript expressions that produce values (e.g., "1 + 2", "x.foo")
  • Stmt - JavaScript statements that perform actions (e.g., "let x = 1", "x++")
  • Callable - Expressions that can have properties accessed or methods called

This type system prevents accidentally passing raw Go strings where JavaScript is expected. The only way to inject arbitrary JavaScript is through the explicit Raw escape hatch.

Creating Values

Use these functions to create JavaScript literals safely:

js.String("hello")     // "hello" (JSON-escaped, prevents XSS)
js.Int(42)             // 42
js.Float(3.14)         // 3.14
js.Bool(true)          // true
js.Null()              // null
js.Undefined()         // undefined

For complex values, use JSON, Array, or Object:

js.JSON(map[string]int{"a": 1})           // {"a":1}
js.Array(js.Int(1), js.Int(2), js.Int(3)) // [1, 2, 3]
js.Object(
    js.Pair("name", js.String("John")),
    js.Pair("age", js.Int(30)),
)                                         // {"name": "John", "age": 30}

To reference JavaScript variables, use Ident:

js.Ident("myVariable")  // myVariable
js.Ident("window")      // window
js.This()               // this

Property and Method Access

Access properties with Prop and call methods with Method:

js.Prop(js.Ident("document"), "body")
// document.body

js.Method(js.Ident("console"), "log", js.String("hello"))
// console.log("hello")

js.Prop(js.Prop(js.Ident("event"), "target"), "value")
// event.target.value

For array/computed property access, use Index:

js.Index(js.Ident("arr"), js.Int(0))         // arr[0]
js.Index(js.Ident("obj"), js.String("key"))  // obj["key"]

Optional chaining is supported with OptionalProp and OptionalCall:

js.OptionalProp(js.Ident("user"), "name")     // user?.name
js.OptionalCall(js.Ident("obj"), "method")    // obj?.method()

Operators

All standard JavaScript operators are available:

// Arithmetic
js.Add(js.Int(1), js.Int(2))    // (1 + 2)
js.Sub(js.Int(5), js.Int(3))    // (5 - 3)
js.Mul(js.Int(4), js.Int(2))    // (4 * 2)
js.Div(js.Int(10), js.Int(2))   // (10 / 2)

// Comparison (strict by default)
js.Eq(js.Ident("x"), js.Int(5))       // (x === 5)
js.NotEq(js.Ident("x"), js.Null())    // (x !== null)
js.Lt(js.Ident("x"), js.Int(10))      // (x < 10)
js.Gt(js.Ident("x"), js.Int(0))       // (x > 0)

// Logical
js.And(js.Ident("a"), js.Ident("b"))  // (a && b)
js.Or(js.Ident("a"), js.Ident("b"))   // (a || b)
js.Not(js.Ident("x"))                 // !x

// Ternary
js.Ternary(js.Ident("cond"), js.String("yes"), js.String("no"))
// (cond ? "yes" : "no")

// Nullish coalescing
js.NullishCoalesce(js.Ident("x"), js.String("default"))
// (x ?? "default")

Statements

Create JavaScript statements for use in handlers:

// Variable declarations
js.Let("x", js.Int(5))           // let x = 5
js.Const("PI", js.Float(3.14))   // const PI = 3.14

// Assignment
js.Assign(js.Ident("x"), js.Int(10))  // x = 10
js.AddAssign(js.Ident("x"), js.Int(1)) // x += 1

// Increment/decrement
js.Incr(js.Ident("count"))  // count++
js.Decr(js.Ident("count"))  // count--

// Conditionals
js.If(js.Eq(js.Ident("x"), js.Int(0)),
    js.Return(js.Null()),
)
// if (x === 0) { return null }

To use an expression as a statement, wrap it with ExprStmt:

js.ExprStmt(js.ConsoleLog(js.String("hello")))
// console.log("hello")

Event Handlers

The Handler function combines statements into a handler string:

handler := js.Handler(
    js.ExprStmt(js.PreventDefault()),
    js.Let("value", js.EventValue()),
    js.ExprStmt(js.ConsoleLog(js.Ident("value"))),
)
// "event.preventDefault(); let value = event.target.value; console.log(value)"

For convenience, use the On* functions to create h.Attribute values directly:

js.OnClick(...)      // onclick="..."
js.OnInput(...)      // oninput="..."
js.OnChange(...)     // onchange="..."
js.OnSubmit(...)     // onsubmit="..."
js.OnKeyDown(...)    // onkeydown="..."
js.OnLoad(...)       // onload="..."

For custom events, use On:

js.On("touchstart", js.ExprStmt(js.ConsoleLog(js.String("touched"))))
// ontouchstart="console.log(\"touched\")"

Built-in Helpers

The package provides helpers for common JavaScript patterns:

Console:

js.ConsoleLog(js.String("message"))   // console.log("message")
js.ConsoleError(js.String("error"))   // console.error("error")
js.ConsoleWarn(js.String("warning"))  // console.warn("warning")

Document:

js.GetElementById(js.String("myId"))     // document.getElementById("myId")
js.QuerySelector(js.String(".myClass"))  // document.querySelector(".myClass")

Event handling:

js.PreventDefault()      // event.preventDefault()
js.StopPropagation()     // event.stopPropagation()
js.EventTarget()         // event.target
js.EventValue()          // event.target.value
js.EventChecked()        // event.target.checked
js.EventKey()            // event.key

Navigation:

js.Navigate(js.String("/home"))  // location.href = "/home"
js.Reload()                      // location.reload()
js.HistoryBack()                 // history.back()

DOM manipulation:

js.ClassListAdd(js.Ident("el"), js.String("active"))
// el.classList.add("active")

js.ClassListToggle(js.Ident("el"), js.String("hidden"))
// el.classList.toggle("hidden")

js.SetStyle(js.Ident("el"), "backgroundColor", js.String("red"))
// el.style.backgroundColor = "red"

Arrow Functions

Create arrow functions for callbacks:

// Expression body
js.ArrowFunc([]string{"x"}, js.Mul(js.Ident("x"), js.Int(2)))
// x => (x * 2)

// Statement body
js.ArrowFuncStmts([]string{"x"},
    js.Let("result", js.Mul(js.Ident("x"), js.Int(2))),
    js.Return(js.Ident("result")),
)
// x => { let result = (x * 2); return result }

// Async arrow functions
js.AsyncArrowFunc([]string{}, js.Await(js.Fetch(js.String("/api"))))
// async () => await fetch("/api")

Template Literals

Create template literals with Template:

js.Template("Hello, ", js.Ident("name"), "!")
// `Hello, ${name}!`

Promises and Async

js.Await(js.Fetch(js.String("/api/data")))
// await fetch("/api/data")

js.PromiseThen(
    js.Fetch(js.String("/api")),
    js.ArrowFunc([]string{"r"}, js.Method(js.Ident("r"), "json")),
)
// fetch("/api").then(r => r.json())

Raw JavaScript Escape Hatch

When you need to inject arbitrary JavaScript that isn't covered by the API, use Raw. This is the ONLY way to inject raw JavaScript and must be used explicitly:

js.Raw("myCustomFunction()")
js.Raw("window.gtag('event', 'click')")

Use Raw sparingly, as it bypasses type safety. The API covers most common use cases, so prefer using the type-safe builders when possible.

Complete Examples

Form submission with validation:

h.Form(
    js.OnSubmit(
        js.ExprStmt(js.PreventDefault()),
        js.Let("email", js.Prop(js.GetElementById(js.String("email")), "value")),
        js.If(js.Eq(js.Ident("email"), js.String("")),
            js.ExprStmt(js.Alert(js.String("Email is required"))),
            js.ReturnVoid(),
        ),
        js.ExprStmt(js.Method(js.This(), "submit")),
    ),
    // ... form fields
)

Toggle visibility:

h.Button(
    js.OnClick(
        js.ExprStmt(js.ClassListToggle(
            js.GetElementById(js.String("panel")),
            js.String("hidden"),
        )),
    ),
    h.Text("Toggle Panel"),
)

Live character count:

h.Textarea(
    h.Attrs("id", "message", "maxlength", "200"),
    js.OnInput(
        js.Assign(
            js.Prop(js.GetElementById(js.String("charCount")), "textContent"),
            js.Template(js.Prop(js.EventValue(), "length"), " / 200"),
        ),
    ),
)

Keyboard shortcuts:

h.Body(
    js.OnKeyDown(
        js.If(js.And(js.EventCtrlKey(), js.Eq(js.EventKey(), js.String("s"))),
            js.ExprStmt(js.PreventDefault()),
            js.ExprStmt(js.Raw("saveDocument()")),
        ),
    ),
)

Fetch with error handling:

h.Button(
    js.OnClick(
        js.ExprStmt(
            js.PromiseCatch(
                js.PromiseThen(
                    js.Fetch(js.String("/api/data")),
                    js.ArrowFunc([]string{"r"}, js.Method(js.Ident("r"), "json")),
                ),
                js.ArrowFunc([]string{"err"}, js.ConsoleError(js.Ident("err"))),
            ),
        ),
    ),
    h.Text("Load Data"),
)
Example (ArrayMethods)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Chain array methods
	expr := js.Method(
		js.Method(js.Ident("items"), "filter", js.ArrowFunc([]string{"x"}, js.Prop(js.Ident("x"), "active"))),
		"map",
		js.ArrowFunc([]string{"x"}, js.Prop(js.Ident("x"), "name")),
	)
	fmt.Println(js.ExprHandler(expr))
}
Output:

items.filter(x => x.active).map(x => x.name)
Example (ArrowFunction)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Create an arrow function for setTimeout
	expr := js.SetTimeout(
		js.ArrowFunc(nil, js.ConsoleLog(js.String("Delayed!"))),
		js.Int(1000),
	)
	fmt.Println(js.ExprHandler(expr))
}
Output:

setTimeout(() => console.log("Delayed!"), 1000)
Example (BasicClickHandler)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	handler := js.Handler(
		js.ExprStmt(js.Alert(js.String("Hello, World!"))),
	)
	fmt.Println(handler)
}
Output:

alert("Hello, World!")
Example (ConditionalLogic)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Show alert if input is empty
	handler := js.Handler(
		js.If(js.Eq(js.EventValue(), js.String("")),
			js.ExprStmt(js.Alert(js.String("Please enter a value"))),
			js.ReturnVoid(),
		),
	)
	fmt.Println(handler)
}
Output:

if ((event.target.value === "")) { alert("Please enter a value"); return }
Example (EventValue)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Transform input to uppercase as the user types
	handler := js.Handler(
		js.Assign(
			js.Prop(js.EventTarget(), "value"),
			js.Method(js.EventValue(), "toUpperCase"),
		),
	)
	fmt.Println(handler)
}
Output:

event.target.value = event.target.value.toUpperCase()
Example (KeyboardShortcut)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Handle Ctrl+S keyboard shortcut
	handler := js.Handler(
		js.If(js.And(js.EventCtrlKey(), js.Eq(js.EventKey(), js.String("s"))),
			js.ExprStmt(js.PreventDefault()),
			js.ExprStmt(js.ConsoleLog(js.String("Save triggered"))),
		),
	)
	fmt.Println(handler)
}
Output:

if ((event.ctrlKey && (event.key === "s"))) { event.preventDefault(); console.log("Save triggered") }
Example (ObjectLiteral)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Create a JavaScript object
	obj := js.Object(
		js.Pair("name", js.String("John")),
		js.Pair("age", js.Int(30)),
		js.Pair("active", js.Bool(true)),
	)
	fmt.Println(js.ExprHandler(obj))
}
Output:

{"name": "John", "age": 30, "active": true}
Example (PreventDefault)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	handler := js.Handler(
		js.ExprStmt(js.PreventDefault()),
		js.ExprStmt(js.ConsoleLog(js.String("Form submitted"))),
	)
	fmt.Println(handler)
}
Output:

event.preventDefault(); console.log("Form submitted")
Example (PromiseChain)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Fetch with promise chain
	expr := js.PromiseCatch(
		js.PromiseThen(
			js.Fetch(js.String("/api/users")),
			js.ArrowFunc([]string{"r"}, js.Method(js.Ident("r"), "json")),
		),
		js.ArrowFunc([]string{"e"}, js.ConsoleError(js.Ident("e"))),
	)
	fmt.Println(js.ExprHandler(expr))
}
Output:

fetch("/api/users").then(r => r.json()).catch(e => console.error(e))
Example (RawEscapeHatch)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Use Raw for custom JavaScript
	handler := js.Handler(
		js.ExprStmt(js.Raw("gtag('event', 'button_click')")),
	)
	fmt.Println(handler)
}
Output:

gtag('event', 'button_click')
Example (TemplateLiteral)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Create a template literal with interpolation
	expr := js.Template("Hello, ", js.Ident("name"), "! You have ", js.Ident("count"), " messages.")
	fmt.Println(js.ExprHandler(expr))
}
Output:

`Hello, ${name}! You have ${count} messages.`
Example (TernaryOperator)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Use ternary for conditional text
	expr := js.Ternary(
		js.Ident("isLoggedIn"),
		js.String("Logout"),
		js.String("Login"),
	)
	fmt.Println(js.ExprHandler(expr))
}
Output:

(isLoggedIn ? "Logout" : "Login")
Example (ToggleClass)
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Toggle a CSS class on an element
	handler := js.Handler(
		js.ExprStmt(js.ClassListToggle(
			js.GetElementById(js.String("menu")),
			js.String("open"),
		)),
	)
	fmt.Println(handler)
}
Output:

document.getElementById("menu").classList.toggle("open")

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Console is the console object
	Console = Ident("console")
	// Document is the document object
	Document = Ident("document")
	// Window is the window object
	Window = Ident("window")
	// Event is the event object in handlers (the event parameter)
	Event = Ident("event")
	// EventThis is the 'this' value in event handlers (the element)
	EventThis = This()
	// Location is the window.location object
	Location = Ident("location")
	// History is the window.history object
	History = Ident("history")
	// Navigator is the window.navigator object
	Navigator = Ident("navigator")
	// LocalStorage is the localStorage object
	LocalStorage = Ident("localStorage")
	// SessionStorage is the sessionStorage object
	SessionStorage = Ident("sessionStorage")
	// JSON_ is the JSON global object (underscore to avoid conflict with JSON() function)
	JSON_ = Ident("JSON")
	// Math is the Math global object
	Math = Ident("Math")
	// Date is the Date constructor
	Date = Ident("Date")
	// Promise is the Promise constructor
	Promise = Ident("Promise")
	// Object_ is the Object constructor
	Object_ = Ident("Object")
	// Array_ is the Array constructor
	Array_ = Ident("Array")
)

Pre-defined global identifiers

Functions

func ExprHandler

func ExprHandler(expr Expr) string

ExprHandler builds an inline JavaScript handler from a single expression.

func Handler

func Handler(stmts ...Stmt) string

Handler builds an inline JavaScript handler string from statements. Statements are joined with semicolons.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Combine multiple statements
	handler := js.Handler(
		js.Let("x", js.Int(1)),
		js.Incr(js.Ident("x")),
		js.ExprStmt(js.ConsoleLog(js.Ident("x"))),
	)
	fmt.Println(handler)
}
Output:

let x = 1; x++; console.log(x)

func On

func On(event string, stmts ...Stmt) h.Attribute

On creates a custom event handler attribute. Example: On("touchstart", stmts...) creates ontouchstart="..."

func OnAfterPrint

func OnAfterPrint(stmts ...Stmt) h.Attribute

OnAfterPrint creates an onafterprint attribute with the given handler.

func OnAnimationEnd

func OnAnimationEnd(stmts ...Stmt) h.Attribute

OnAnimationEnd creates an onanimationend attribute with the given handler.

func OnAnimationIteration

func OnAnimationIteration(stmts ...Stmt) h.Attribute

OnAnimationIteration creates an onanimationiteration attribute with the given handler.

func OnAnimationStart

func OnAnimationStart(stmts ...Stmt) h.Attribute

OnAnimationStart creates an onanimationstart attribute with the given handler.

func OnBeforePrint

func OnBeforePrint(stmts ...Stmt) h.Attribute

OnBeforePrint creates an onbeforeprint attribute with the given handler.

func OnBeforeUnload

func OnBeforeUnload(stmts ...Stmt) h.Attribute

OnBeforeUnload creates an onbeforeunload attribute with the given handler.

func OnBlur

func OnBlur(stmts ...Stmt) h.Attribute

OnBlur creates an onblur attribute with the given handler.

func OnCanPlay

func OnCanPlay(stmts ...Stmt) h.Attribute

OnCanPlay creates an oncanplay attribute with the given handler.

func OnCanPlayThrough

func OnCanPlayThrough(stmts ...Stmt) h.Attribute

OnCanPlayThrough creates an oncanplaythrough attribute with the given handler.

func OnChange

func OnChange(stmts ...Stmt) h.Attribute

OnChange creates an onchange attribute with the given handler.

func OnClick

func OnClick(stmts ...Stmt) h.Attribute

OnClick creates an onclick attribute with the given handler.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	attr := js.OnClick(js.ExprStmt(js.ConsoleLog(js.String("clicked"))))
	fmt.Printf("%s=%q", attr.Name, attr.Value)
}
Output:

onclick="console.log(\"clicked\")"

func OnContextMenu

func OnContextMenu(stmts ...Stmt) h.Attribute

OnContextMenu creates an oncontextmenu attribute with the given handler.

func OnCopy

func OnCopy(stmts ...Stmt) h.Attribute

OnCopy creates an oncopy attribute with the given handler.

func OnCut

func OnCut(stmts ...Stmt) h.Attribute

OnCut creates an oncut attribute with the given handler.

func OnDblClick

func OnDblClick(stmts ...Stmt) h.Attribute

OnDblClick creates an ondblclick attribute with the given handler.

func OnDrag

func OnDrag(stmts ...Stmt) h.Attribute

OnDrag creates an ondrag attribute with the given handler.

func OnDragEnd

func OnDragEnd(stmts ...Stmt) h.Attribute

OnDragEnd creates an ondragend attribute with the given handler.

func OnDragEnter

func OnDragEnter(stmts ...Stmt) h.Attribute

OnDragEnter creates an ondragenter attribute with the given handler.

func OnDragLeave

func OnDragLeave(stmts ...Stmt) h.Attribute

OnDragLeave creates an ondragleave attribute with the given handler.

func OnDragOver

func OnDragOver(stmts ...Stmt) h.Attribute

OnDragOver creates an ondragover attribute with the given handler.

func OnDragStart

func OnDragStart(stmts ...Stmt) h.Attribute

OnDragStart creates an ondragstart attribute with the given handler.

func OnDrop

func OnDrop(stmts ...Stmt) h.Attribute

OnDrop creates an ondrop attribute with the given handler.

func OnEnded

func OnEnded(stmts ...Stmt) h.Attribute

OnEnded creates an onended attribute with the given handler.

func OnError

func OnError(stmts ...Stmt) h.Attribute

OnError creates an onerror attribute with the given handler.

func OnFocus

func OnFocus(stmts ...Stmt) h.Attribute

OnFocus creates an onfocus attribute with the given handler.

func OnFocusIn

func OnFocusIn(stmts ...Stmt) h.Attribute

OnFocusIn creates an onfocusin attribute with the given handler.

func OnFocusOut

func OnFocusOut(stmts ...Stmt) h.Attribute

OnFocusOut creates an onfocusout attribute with the given handler.

func OnHashChange

func OnHashChange(stmts ...Stmt) h.Attribute

OnHashChange creates an onhashchange attribute with the given handler.

func OnInput

func OnInput(stmts ...Stmt) h.Attribute

OnInput creates an oninput attribute with the given handler.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	attr := js.OnInput(
		js.Assign(js.Ident("value"), js.EventValue()),
	)
	fmt.Printf("%s=%q", attr.Name, attr.Value)
}
Output:

oninput="value = event.target.value"

func OnInvalid

func OnInvalid(stmts ...Stmt) h.Attribute

OnInvalid creates an oninvalid attribute with the given handler.

func OnKeyDown

func OnKeyDown(stmts ...Stmt) h.Attribute

OnKeyDown creates an onkeydown attribute with the given handler.

func OnKeyPress

func OnKeyPress(stmts ...Stmt) h.Attribute

OnKeyPress creates an onkeypress attribute with the given handler. Deprecated: Use OnKeyDown or OnKeyUp instead.

func OnKeyUp

func OnKeyUp(stmts ...Stmt) h.Attribute

OnKeyUp creates an onkeyup attribute with the given handler.

func OnLoad

func OnLoad(stmts ...Stmt) h.Attribute

OnLoad creates an onload attribute with the given handler.

func OnLoadedData

func OnLoadedData(stmts ...Stmt) h.Attribute

OnLoadedData creates an onloadeddata attribute with the given handler.

func OnLoadedMetadata

func OnLoadedMetadata(stmts ...Stmt) h.Attribute

OnLoadedMetadata creates an onloadedmetadata attribute with the given handler.

func OnMouseDown

func OnMouseDown(stmts ...Stmt) h.Attribute

OnMouseDown creates an onmousedown attribute with the given handler.

func OnMouseEnter

func OnMouseEnter(stmts ...Stmt) h.Attribute

OnMouseEnter creates an onmouseenter attribute with the given handler.

func OnMouseLeave

func OnMouseLeave(stmts ...Stmt) h.Attribute

OnMouseLeave creates an onmouseleave attribute with the given handler.

func OnMouseMove

func OnMouseMove(stmts ...Stmt) h.Attribute

OnMouseMove creates an onmousemove attribute with the given handler.

func OnMouseOut

func OnMouseOut(stmts ...Stmt) h.Attribute

OnMouseOut creates an onmouseout attribute with the given handler.

func OnMouseOver

func OnMouseOver(stmts ...Stmt) h.Attribute

OnMouseOver creates an onmouseover attribute with the given handler.

func OnMouseUp

func OnMouseUp(stmts ...Stmt) h.Attribute

OnMouseUp creates an onmouseup attribute with the given handler.

func OnOffline

func OnOffline(stmts ...Stmt) h.Attribute

OnOffline creates an onoffline attribute with the given handler.

func OnOnline

func OnOnline(stmts ...Stmt) h.Attribute

OnOnline creates an ononline attribute with the given handler.

func OnPaste

func OnPaste(stmts ...Stmt) h.Attribute

OnPaste creates an onpaste attribute with the given handler.

func OnPause

func OnPause(stmts ...Stmt) h.Attribute

OnPause creates an onpause attribute with the given handler.

func OnPlay

func OnPlay(stmts ...Stmt) h.Attribute

OnPlay creates an onplay attribute with the given handler.

func OnPointerCancel

func OnPointerCancel(stmts ...Stmt) h.Attribute

OnPointerCancel creates an onpointercancel attribute with the given handler.

func OnPointerDown

func OnPointerDown(stmts ...Stmt) h.Attribute

OnPointerDown creates an onpointerdown attribute with the given handler.

func OnPointerEnter

func OnPointerEnter(stmts ...Stmt) h.Attribute

OnPointerEnter creates an onpointerenter attribute with the given handler.

func OnPointerLeave

func OnPointerLeave(stmts ...Stmt) h.Attribute

OnPointerLeave creates an onpointerleave attribute with the given handler.

func OnPointerMove

func OnPointerMove(stmts ...Stmt) h.Attribute

OnPointerMove creates an onpointermove attribute with the given handler.

func OnPointerOut

func OnPointerOut(stmts ...Stmt) h.Attribute

OnPointerOut creates an onpointerout attribute with the given handler.

func OnPointerOver

func OnPointerOver(stmts ...Stmt) h.Attribute

OnPointerOver creates an onpointerover attribute with the given handler.

func OnPointerUp

func OnPointerUp(stmts ...Stmt) h.Attribute

OnPointerUp creates an onpointerup attribute with the given handler.

func OnPopState

func OnPopState(stmts ...Stmt) h.Attribute

OnPopState creates an onpopstate attribute with the given handler.

func OnReset

func OnReset(stmts ...Stmt) h.Attribute

OnReset creates an onreset attribute with the given handler.

func OnResize

func OnResize(stmts ...Stmt) h.Attribute

OnResize creates an onresize attribute with the given handler.

func OnScroll

func OnScroll(stmts ...Stmt) h.Attribute

OnScroll creates an onscroll attribute with the given handler.

func OnSeeked

func OnSeeked(stmts ...Stmt) h.Attribute

OnSeeked creates an onseeked attribute with the given handler.

func OnSeeking

func OnSeeking(stmts ...Stmt) h.Attribute

OnSeeking creates an onseeking attribute with the given handler.

func OnSelect

func OnSelect(stmts ...Stmt) h.Attribute

OnSelect creates an onselect attribute with the given handler.

func OnStorage

func OnStorage(stmts ...Stmt) h.Attribute

OnStorage creates an onstorage attribute with the given handler.

func OnSubmit

func OnSubmit(stmts ...Stmt) h.Attribute

OnSubmit creates an onsubmit attribute with the given handler.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	attr := js.OnSubmit(
		js.ExprStmt(js.PreventDefault()),
		js.ExprStmt(js.Method(js.This(), "submit")),
	)
	fmt.Printf("%s=%q", attr.Name, attr.Value)
}
Output:

onsubmit="event.preventDefault(); this.submit()"

func OnTimeUpdate

func OnTimeUpdate(stmts ...Stmt) h.Attribute

OnTimeUpdate creates an ontimeupdate attribute with the given handler.

func OnTouchCancel

func OnTouchCancel(stmts ...Stmt) h.Attribute

OnTouchCancel creates an ontouchcancel attribute with the given handler.

func OnTouchEnd

func OnTouchEnd(stmts ...Stmt) h.Attribute

OnTouchEnd creates an ontouchend attribute with the given handler.

func OnTouchMove

func OnTouchMove(stmts ...Stmt) h.Attribute

OnTouchMove creates an ontouchmove attribute with the given handler.

func OnTouchStart

func OnTouchStart(stmts ...Stmt) h.Attribute

OnTouchStart creates an ontouchstart attribute with the given handler.

func OnTransitionCancel

func OnTransitionCancel(stmts ...Stmt) h.Attribute

OnTransitionCancel creates an ontransitioncancel attribute with the given handler.

func OnTransitionEnd

func OnTransitionEnd(stmts ...Stmt) h.Attribute

OnTransitionEnd creates an ontransitionend attribute with the given handler.

func OnTransitionRun

func OnTransitionRun(stmts ...Stmt) h.Attribute

OnTransitionRun creates an ontransitionrun attribute with the given handler.

func OnTransitionStart

func OnTransitionStart(stmts ...Stmt) h.Attribute

OnTransitionStart creates an ontransitionstart attribute with the given handler.

func OnUnload

func OnUnload(stmts ...Stmt) h.Attribute

OnUnload creates an onunload attribute with the given handler.

func OnVolumeChange

func OnVolumeChange(stmts ...Stmt) h.Attribute

OnVolumeChange creates an onvolumechange attribute with the given handler.

func OnWheel

func OnWheel(stmts ...Stmt) h.Attribute

OnWheel creates an onwheel attribute with the given handler.

func ToJS

func ToJS(expr Expr) string

ToJS converts an expression to its JavaScript string representation.

func ToJSStmt

func ToJSStmt(stmt Stmt) string

ToJSStmt converts a statement to its JavaScript string representation.

Types

type Callable

type Callable interface {
	Expr
	// contains filtered or unexported methods
}

Callable represents a JavaScript value that can have properties accessed and methods called on it (identifiers, objects, function results).

func Add

func Add(left, right Expr) Callable

Add returns left + right

func Alert

func Alert(message Expr) Callable

Alert creates alert(message)

func And

func And(left, right Expr) Callable

And returns left && right

func AppendChild

func AppendChild(parent, child Callable) Callable

AppendChild creates parent.appendChild(child)

func Array

func Array(elements ...Expr) Callable

Array creates a JavaScript array literal from expressions.

func ArrowFunc

func ArrowFunc(params []string, body Expr) Callable

ArrowFunc creates an arrow function expression with a single expression body. Example: ArrowFunc([]string{"x", "y"}, Add(Ident("x"), Ident("y")))

=> (x, y) => (x + y)
Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Single expression arrow function
	fn := js.ArrowFunc([]string{"a", "b"}, js.Add(js.Ident("a"), js.Ident("b")))
	fmt.Println(js.ExprHandler(fn))
}
Output:

(a, b) => (a + b)

func ArrowFuncStmts

func ArrowFuncStmts(params []string, stmts ...Stmt) Callable

ArrowFuncStmts creates an arrow function with a statement body. Example: ArrowFuncStmts([]string{"e"}, ExprStmt(ConsoleLog(Ident("e"))))

=> (e) => { console.log(e) }
Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Multi-statement arrow function
	fn := js.ArrowFuncStmts([]string{"x"},
		js.Let("result", js.Mul(js.Ident("x"), js.Int(2))),
		js.Return(js.Ident("result")),
	)
	fmt.Println(js.ExprHandler(fn))
}
Output:

x => { let result = (x * 2); return result }

func AsyncArrowFunc

func AsyncArrowFunc(params []string, body Expr) Callable

AsyncArrowFunc creates an async arrow function with a single expression body. Example: AsyncArrowFunc([]string{}, Await(Fetch(String("/api"))))

=> async () => await fetch("/api")
Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	fn := js.AsyncArrowFunc([]string{"url"},
		js.Await(js.Fetch(js.Ident("url"))),
	)
	fmt.Println(js.ExprHandler(fn))
}
Output:

async url => await fetch(url)

func AsyncArrowFuncStmts

func AsyncArrowFuncStmts(params []string, stmts ...Stmt) Callable

AsyncArrowFuncStmts creates an async arrow function with a statement body. Example: AsyncArrowFuncStmts([]string{}, Let("data", Await(Fetch(String("/api")))))

=> async () => { let data = await fetch("/api") }

func Await

func Await(expr Expr) Callable

Await creates an await expression. Example: Await(Fetch(String("/api/data")))

=> await fetch("/api/data")
Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	expr := js.Await(js.Method(js.Fetch(js.String("/api")), "json"))
	fmt.Println(js.ExprHandler(expr))
}
Output:

await fetch("/api").json()

func BitwiseAnd

func BitwiseAnd(left, right Expr) Callable

BitwiseAnd returns left & right

func BitwiseNot

func BitwiseNot(expr Expr) Callable

BitwiseNot returns ~expr

func BitwiseOr

func BitwiseOr(left, right Expr) Callable

BitwiseOr returns left | right

func BitwiseXor

func BitwiseXor(left, right Expr) Callable

BitwiseXor returns left ^ right

func Blur

func Blur(element Callable) Callable

Blur creates element.blur()

func BlurThis

func BlurThis() Callable

BlurThis creates this.blur() (for use in event handlers)

func Bool

func Bool(b bool) Callable

Bool creates a JavaScript boolean literal.

func Call

func Call(fn Callable, args ...Expr) Callable

Call invokes a callable with arguments. Example: Call(Ident("alert"), String("hello")) => alert("hello")

func CancelAnimationFrame

func CancelAnimationFrame(id Expr) Callable

CancelAnimationFrame creates cancelAnimationFrame(id)

func ClassList

func ClassList(element Callable) Callable

ClassList creates element.classList

func ClassListAdd

func ClassListAdd(element Callable, classes ...Expr) Callable

ClassListAdd creates element.classList.add(classes...)

func ClassListContains

func ClassListContains(element Callable, className Expr) Callable

ClassListContains creates element.classList.contains(className)

func ClassListRemove

func ClassListRemove(element Callable, classes ...Expr) Callable

ClassListRemove creates element.classList.remove(classes...)

func ClassListReplace

func ClassListReplace(element Callable, oldClass, newClass Expr) Callable

ClassListReplace creates element.classList.replace(oldClass, newClass)

func ClassListToggle

func ClassListToggle(element Callable, className Expr, force ...Expr) Callable

ClassListToggle creates element.classList.toggle(className, force?)

func ClearInterval

func ClearInterval(id Expr) Callable

ClearInterval creates clearInterval(id)

func ClearStorage

func ClearStorage(storage Callable) Callable

ClearStorage creates storage.clear()

func ClearTimeout

func ClearTimeout(id Expr) Callable

ClearTimeout creates clearTimeout(id)

func Click

func Click(element Callable) Callable

Click creates element.click()

func CloneNode

func CloneNode(element Callable, deep Expr) Callable

CloneNode creates element.cloneNode(deep)

func Comma

func Comma(exprs ...Expr) Callable

Comma creates a comma expression that evaluates all expressions and returns the value of the last one.

func Confirm

func Confirm(message Expr) Callable

Confirm creates confirm(message)

func ConsoleClear

func ConsoleClear() Callable

ConsoleClear creates console.clear()

func ConsoleDebug

func ConsoleDebug(args ...Expr) Callable

ConsoleDebug creates console.debug(args...)

func ConsoleError

func ConsoleError(args ...Expr) Callable

ConsoleError creates console.error(args...)

func ConsoleInfo

func ConsoleInfo(args ...Expr) Callable

ConsoleInfo creates console.info(args...)

func ConsoleLog

func ConsoleLog(args ...Expr) Callable

ConsoleLog creates console.log(args...)

func ConsoleTable

func ConsoleTable(data Expr) Callable

ConsoleTable creates console.table(data)

func ConsoleWarn

func ConsoleWarn(args ...Expr) Callable

ConsoleWarn creates console.warn(args...)

func CreateElement

func CreateElement(tag Expr) Callable

CreateElement creates document.createElement(tag)

func CreateTextNode

func CreateTextNode(text Expr) Callable

CreateTextNode creates document.createTextNode(text)

func DecodeURI

func DecodeURI(uri Expr) Callable

DecodeURI creates decodeURI(uri)

func DecodeURIComponent

func DecodeURIComponent(component Expr) Callable

DecodeURIComponent creates decodeURIComponent(component)

func Delete

func Delete(expr Expr) Callable

Delete returns delete expr

func Div

func Div(left, right Expr) Callable

Div returns left / right

func EncodeURI

func EncodeURI(uri Expr) Callable

Encodeuri creates encodeURI(uri)

func EncodeURIComponent

func EncodeURIComponent(component Expr) Callable

EncodeURIComponent creates encodeURIComponent(component)

func Eq

func Eq(left, right Expr) Callable

Eq returns left === right (strict equality)

func EventAltKey

func EventAltKey() Callable

EventAltKey creates event.altKey

func EventChecked

func EventChecked() Callable

EventChecked creates event.target.checked (common for checkbox handlers)

func EventCode

func EventCode() Callable

EventCode creates event.code (for keyboard events)

func EventCtrlKey

func EventCtrlKey() Callable

EventCtrlKey creates event.ctrlKey

func EventCurrentTarget

func EventCurrentTarget() Callable

EventCurrentTarget creates event.currentTarget

func EventKey

func EventKey() Callable

EventKey creates event.key (for keyboard events)

func EventKeyCode

func EventKeyCode() Callable

EventKeyCode creates event.keyCode (for keyboard events, deprecated but common)

func EventMetaKey

func EventMetaKey() Callable

EventMetaKey creates event.metaKey

func EventShiftKey

func EventShiftKey() Callable

EventShiftKey creates event.shiftKey

func EventTarget

func EventTarget() Callable

EventTarget creates event.target

func EventValue

func EventValue() Callable

EventValue creates event.target.value (common for input handlers)

func EventWhich

func EventWhich() Callable

EventWhich creates event.which (for keyboard events, deprecated but common)

func Fetch

func Fetch(url Expr, options ...Expr) Callable

Fetch creates fetch(url, options)

func Float

func Float(f float64) Callable

Float creates a JavaScript number literal from a float64.

func Focus

func Focus(element Callable) Callable

Focus creates element.focus()

func FocusThis

func FocusThis() Callable

FocusThis creates this.focus() (for use in event handlers)

func Func

func Func(params []string, stmts ...Stmt) Callable

Func creates an anonymous function expression. Example: Func([]string{"x", "y"}, Return(Add(Ident("x"), Ident("y"))))

=> function(x, y) { return (x + y) }

func GetAttribute

func GetAttribute(element Callable, name Expr) Callable

GetAttribute creates element.getAttribute(name)

func GetElementById

func GetElementById(id Expr) Callable

GetElementById creates document.getElementById(id)

func GetElementsByClassName

func GetElementsByClassName(className Expr) Callable

GetElementsByClassName creates document.getElementsByClassName(className)

func GetElementsByTagName

func GetElementsByTagName(tagName Expr) Callable

GetElementsByTagName creates document.getElementsByTagName(tagName)

func GetItem

func GetItem(storage Callable, key Expr) Callable

GetItem creates storage.getItem(key)

func Group

func Group(expr Expr) Callable

Group wraps an expression in parentheses.

func Gt

func Gt(left, right Expr) Callable

Gt returns left > right

func GtEq

func GtEq(left, right Expr) Callable

GtEq returns left >= right

func HasAttribute

func HasAttribute(element Callable, name Expr) Callable

HasAttribute creates element.hasAttribute(name)

func HistoryBack

func HistoryBack() Callable

HistoryBack creates history.back()

func HistoryForward

func HistoryForward() Callable

HistoryForward creates history.forward()

func HistoryGo

func HistoryGo(delta Expr) Callable

HistoryGo creates history.go(delta)

func HistoryPushState

func HistoryPushState(state, title, url Expr) Callable

HistoryPushState creates history.pushState(state, title, url)

func HistoryReplaceState

func HistoryReplaceState(state, title, url Expr) Callable

HistoryReplaceState creates history.replaceState(state, title, url)

func IIFE

func IIFE(stmts ...Stmt) Callable

IIFE creates an immediately invoked function expression. Example: IIFE(ExprStmt(ConsoleLog(String("hello"))))

=> (function() { console.log("hello") })()

func Ident

func Ident(name string) Callable

Ident creates a JavaScript identifier reference. This should be used for variable names, not for string literals.

func In

func In(left, right Expr) Callable

In returns left in right

func Index

func Index(obj Callable, index Expr) Callable

Index accesses an element by index or computed property. Example: Index(Ident("arr"), Int(0)) => arr[0] Example: Index(Ident("obj"), String("key")) => obj["key"]

func InsertBefore

func InsertBefore(parent, newNode, referenceNode Callable) Callable

InsertBefore creates parent.insertBefore(newNode, referenceNode)

func Instanceof

func Instanceof(left, right Expr) Callable

Instanceof returns left instanceof right

func Int

func Int(n int) Callable

Int creates a JavaScript number literal from an integer.

func Int64

func Int64(n int64) Callable

Int64 creates a JavaScript number literal from an int64.

func IsFinite

func IsFinite(value Expr) Callable

IsFinite creates isFinite(value)

func IsNaN

func IsNaN(value Expr) Callable

IsNaN creates isNaN(value)

func JSON

func JSON(value any) Callable

JSON creates a JavaScript value from a Go value using JSON encoding. Panics if the value cannot be marshaled to JSON.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// JSON encodes any Go value
	expr := js.JSON(map[string]any{
		"users": []string{"alice", "bob"},
	})
	fmt.Println(js.ExprHandler(expr))
}
Output:

{"users":["alice","bob"]}

func JSONParse

func JSONParse(text Expr, reviver ...Expr) Callable

JSONParse creates JSON.parse(text, reviver?)

func JSONStringify

func JSONStringify(value Expr, args ...Expr) Callable

JSONStringify creates JSON.stringify(value, replacer?, space?)

func LooseEq

func LooseEq(left, right Expr) Callable

LooseEq returns left == right (loose equality)

func LooseNotEq

func LooseNotEq(left, right Expr) Callable

LooseNotEq returns left != right (loose inequality)

func Lt

func Lt(left, right Expr) Callable

Lt returns left < right

func LtEq

func LtEq(left, right Expr) Callable

LtEq returns left <= right

func Method

func Method(obj Callable, method string, args ...Expr) Callable

Method calls a method on an object with arguments. Example: Method(Ident("console"), "log", String("hello")) => console.log("hello")

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Call a method with arguments
	expr := js.Method(js.Ident("arr"), "push", js.Int(1), js.Int(2))
	fmt.Println(js.ExprHandler(expr))
}
Output:

arr.push(1, 2)

func Mod

func Mod(left, right Expr) Callable

Mod returns left % right

func Mul

func Mul(left, right Expr) Callable

Mul returns left * right

func Neg

func Neg(expr Expr) Callable

Neg returns -expr (negation)

func New

func New(constructor Callable, args ...Expr) Callable

New creates a new instance with the new keyword. Example: New(Ident("Date")) => new Date()

func Not

func Not(expr Expr) Callable

Not returns !expr

func NotEq

func NotEq(left, right Expr) Callable

NotEq returns left !== right (strict inequality)

func Null

func Null() Callable

Null creates a JavaScript null literal.

func NullishCoalesce

func NullishCoalesce(left, right Expr) Callable

NullishCoalesce returns left ?? right

func Object

func Object(pairs ...KV) Callable

Object creates a JavaScript object literal from key-value pairs.

func OptionalCall

func OptionalCall(obj Callable, method string, args ...Expr) Callable

OptionalCall calls a method with optional chaining. Example: OptionalCall(Ident("obj"), "method", args...) => obj?.method(args...)

func OptionalProp

func OptionalProp(obj Callable, name string) Callable

OptionalProp accesses a property with optional chaining. Example: OptionalProp(Ident("obj"), "foo") => obj?.foo

func Or

func Or(left, right Expr) Callable

Or returns left || right

func ParseFloat

func ParseFloat(str Expr) Callable

ParseFloat creates parseFloat(string)

func ParseInt

func ParseInt(str Expr, radix ...Expr) Callable

ParseInt creates parseInt(string, radix)

func Pos

func Pos(expr Expr) Callable

Pos returns +expr (unary plus)

func PostDecr

func PostDecr(target Callable) Callable

PostDecr creates: target-- (usable as expression)

func PostIncr

func PostIncr(target Callable) Callable

PostIncr creates: target++ (usable as expression)

func PreDecr

func PreDecr(target Callable) Callable

PreDecr creates: --target (usable as expression)

func PreIncr

func PreIncr(target Callable) Callable

PreIncr creates: ++target (usable as expression)

func PreventDefault

func PreventDefault() Callable

PreventDefault creates event.preventDefault()

func PromiseAll

func PromiseAll(iterable Expr) Callable

PromiseAll creates Promise.all(iterable)

func PromiseCatch

func PromiseCatch(promise Callable, onRejected Expr) Callable

PromiseCatch creates expr.catch(onRejected)

func PromiseFinally

func PromiseFinally(promise Callable, onFinally Expr) Callable

PromiseFinally creates expr.finally(onFinally)

func PromiseRace

func PromiseRace(iterable Expr) Callable

PromiseRace creates Promise.race(iterable)

func PromiseReject

func PromiseReject(reason Expr) Callable

PromiseReject creates Promise.reject(reason)

func PromiseResolve

func PromiseResolve(value Expr) Callable

PromiseResolve creates Promise.resolve(value)

func PromiseThen

func PromiseThen(promise Callable, onFulfilled Expr) Callable

PromiseThen creates expr.then(onFulfilled)

func Prompt

func Prompt(message Expr, defaultValue ...Expr) Callable

Prompt creates prompt(message, defaultValue)

func Prop

func Prop(obj Callable, name string) Callable

Prop accesses a property on a callable expression. Example: Prop(Ident("document"), "body") => document.body

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Access nested properties
	expr := js.Prop(js.Prop(js.Ident("window"), "location"), "href")
	fmt.Println(js.ExprHandler(expr))
}
Output:

window.location.href

func QuerySelector

func QuerySelector(selector Expr) Callable

QuerySelector creates document.querySelector(selector)

func QuerySelectorAll

func QuerySelectorAll(selector Expr) Callable

QuerySelectorAll creates document.querySelectorAll(selector)

func Raw

func Raw(code string) Callable

Raw injects raw JavaScript code. This is the ONLY way to inject arbitrary JS. Use with caution as this bypasses type safety.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Raw is the escape hatch for arbitrary JavaScript
	expr := js.Raw("customLibrary.doSomething()")
	fmt.Println(js.ExprHandler(expr))
}
Output:

customLibrary.doSomething()

func Reload

func Reload() Callable

Reload creates location.reload()

func Remove

func Remove(element Callable) Callable

Remove creates element.remove()

func RemoveAttribute

func RemoveAttribute(element Callable, name Expr) Callable

RemoveAttribute creates element.removeAttribute(name)

func RemoveChild

func RemoveChild(parent, child Callable) Callable

RemoveChild creates parent.removeChild(child)

func RemoveItem

func RemoveItem(storage Callable, key Expr) Callable

RemoveItem creates storage.removeItem(key)

func ReplaceChild

func ReplaceChild(parent, newChild, oldChild Callable) Callable

ReplaceChild creates parent.replaceChild(newChild, oldChild)

func RequestAnimationFrame

func RequestAnimationFrame(callback Expr) Callable

RequestAnimationFrame creates requestAnimationFrame(callback)

func Select

func Select(element Callable) Callable

Select creates element.select()

func SetAttribute

func SetAttribute(element, name, value Expr) Callable

SetAttribute creates element.setAttribute(name, value)

func SetInterval

func SetInterval(callback, interval Expr) Callable

SetInterval creates setInterval(callback, interval)

func SetItem

func SetItem(storage Callable, key, value Expr) Callable

SetItem creates storage.setItem(key, value)

func SetTimeout

func SetTimeout(callback, delay Expr) Callable

SetTimeout creates setTimeout(callback, delay)

func ShiftLeft

func ShiftLeft(left, right Expr) Callable

ShiftLeft returns left << right

func ShiftRight

func ShiftRight(left, right Expr) Callable

ShiftRight returns left >> right

func Spread

func Spread(expr Expr) Callable

Spread creates a spread expression: ...expr

func StopImmediatePropagation

func StopImmediatePropagation() Callable

StopImmediatePropagation creates event.stopImmediatePropagation()

func StopPropagation

func StopPropagation() Callable

StopPropagation creates event.stopPropagation()

func String

func String(s string) Callable

String creates a JavaScript string literal, properly escaped using JSON encoding.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Strings are JSON-encoded for safety
	expr := js.String(`He said "hello"`)
	fmt.Println(js.ExprHandler(expr))
}
Output:

"He said \"hello\""

func Style

func Style(element Callable) Callable

Style creates element.style

func Sub

func Sub(left, right Expr) Callable

Sub returns left - right

func Template

func Template(parts ...any) Callable

Template creates a template literal expression. Alternates between string parts and expression parts. Example: Template("Hello, ", Ident("name"), "!")

=> `Hello, ${name}!`
Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	expr := js.Template("User: ", js.Ident("name"), " (", js.Ident("id"), ")")
	fmt.Println(js.ExprHandler(expr))
}
Output:

`User: ${name} (${id})`

func Ternary

func Ternary(cond, ifTrue, ifFalse Expr) Callable

Ternary returns cond ? ifTrue : ifFalse

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	expr := js.Ternary(
		js.Gt(js.Ident("age"), js.Int(18)),
		js.String("adult"),
		js.String("minor"),
	)
	fmt.Println(js.ExprHandler(expr))
}
Output:

((age > 18) ? "adult" : "minor")

func This

func This() Callable

This creates the special "this" identifier.

func Typeof

func Typeof(expr Expr) Callable

Typeof returns typeof expr

func Undefined

func Undefined() Callable

Undefined creates a JavaScript undefined literal.

func UnsignedShiftRight

func UnsignedShiftRight(left, right Expr) Callable

UnsignedShiftRight returns left >>> right

func Void

func Void(expr Expr) Callable

Void returns void expr

type Expr

type Expr interface {
	// contains filtered or unexported methods
}

Expr represents a JavaScript expression that produces a value. Expressions can be composed into larger expressions or used as statements.

type KV

type KV struct {
	Key   string
	Value Expr
}

KV represents a key-value pair for object literals.

func Pair

func Pair(key string, value Expr) KV

Pair creates a key-value pair for Object().

type Stmt

type Stmt interface {
	// contains filtered or unexported methods
}

Stmt represents a JavaScript statement. Statements are complete units of execution.

func AddAssign

func AddAssign(target Callable, value Expr) Stmt

AddAssign creates: target += value

func AndAssign

func AndAssign(target Callable, value Expr) Stmt

AndAssign creates: target &&= value

func Assign

func Assign(target Callable, value Expr) Stmt

Assign creates an assignment statement: target = value

func Block

func Block(body ...Stmt) Stmt

Block creates a block statement: { body... }

func Break

func Break() Stmt

Break creates a break statement

func BreakLabel

func BreakLabel(label string) Stmt

BreakLabel creates a break statement with a label: break label

func Const

func Const(name string, value Expr) Stmt

Const creates a const declaration: const name = value

func Continue

func Continue() Stmt

Continue creates a continue statement

func ContinueLabel

func ContinueLabel(label string) Stmt

ContinueLabel creates a continue statement with a label: continue label

func Debugger

func Debugger() Stmt

Debugger creates a debugger statement

func Decr

func Decr(target Callable) Stmt

Decr creates: target-- (post-decrement statement)

func DivAssign

func DivAssign(target Callable, value Expr) Stmt

DivAssign creates: target /= value

func ExprStmt

func ExprStmt(expr Expr) Stmt

ExprStmt converts an expression to a statement.

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	// Convert an expression to a statement
	stmt := js.ExprStmt(js.ConsoleLog(js.String("hello")))
	fmt.Println(js.ToJSStmt(stmt))
}
Output:

console.log("hello")

func If

func If(cond Expr, body ...Stmt) Stmt

If creates an if statement: if (cond) { body... }

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	stmt := js.If(js.Gt(js.Ident("x"), js.Int(0)),
		js.ExprStmt(js.ConsoleLog(js.String("positive"))),
	)
	fmt.Println(js.ToJSStmt(stmt))
}
Output:

if ((x > 0)) { console.log("positive") }

func IfElse

func IfElse(cond Expr, thenBody []Stmt, elseBody []Stmt) Stmt

IfElse creates an if-else statement: if (cond) { thenBody... } else { elseBody... }

Example
package main

import (
	"fmt"

	"github.com/jeffh/htmlgen/js"
)

func main() {
	stmt := js.IfElse(
		js.Gt(js.Ident("x"), js.Int(0)),
		[]js.Stmt{js.Return(js.String("positive"))},
		[]js.Stmt{js.Return(js.String("non-positive"))},
	)
	fmt.Println(js.ToJSStmt(stmt))
}
Output:

if ((x > 0)) { return "positive" } else { return "non-positive" }

func Incr

func Incr(target Callable) Stmt

Incr creates: target++ (post-increment statement)

func Let

func Let(name string, value Expr) Stmt

Let creates a let declaration: let name = value

func LetDecl

func LetDecl(name string) Stmt

LetDecl creates a let declaration without initialization: let name

func ModAssign

func ModAssign(target Callable, value Expr) Stmt

ModAssign creates: target %= value

func MulAssign

func MulAssign(target Callable, value Expr) Stmt

MulAssign creates: target *= value

func Navigate(url Expr) Stmt

Navigate creates location.href = url

func NullishAssign

func NullishAssign(target Callable, value Expr) Stmt

NullishAssign creates: target ??= value

func OrAssign

func OrAssign(target Callable, value Expr) Stmt

OrAssign creates: target ||= value

func Return

func Return(value Expr) Stmt

Return creates a return statement: return value

func ReturnVoid

func ReturnVoid() Stmt

ReturnVoid creates a bare return statement: return

func SetStyle

func SetStyle(element Callable, property string, value Expr) Stmt

SetStyle creates element.style.property = value

func Stmts

func Stmts(stmts ...Stmt) Stmt

Stmts combines multiple statements (semicolon-separated).

func SubAssign

func SubAssign(target Callable, value Expr) Stmt

SubAssign creates: target -= value

func Throw

func Throw(value Expr) Stmt

Throw creates a throw statement: throw value

func Var

func Var(name string, value Expr) Stmt

Var creates a var declaration: var name = value

func VarDecl

func VarDecl(name string) Stmt

VarDecl creates a var declaration without initialization: var name

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL