js
Command (inline)Note: This page is about the inline JS command. _hyperscript also supports JS blocks at the top level.
js[(<param-list>)] <js-body> end
param-list
is a comma separated list of identifiers, which are _hyperscript variables whose values will be passed to this JavaScript code and become available there under their original namejs-body
is some JavaScript code whose return value will be the result of this command (what it
refers to in the next command).The js
command can be used to embed JavaScript code inline in _hyperscript, as shown below:
<button
_="on click
js
if ('clipboard' in window.navigator) {
return navigator.clipboard.readText()
}
end
put it in my.innerHTML "
></button>
this
inside a js
block is the global scope (window
, or self
in workers).
If the js
block returns a promise, the code that comes after it will execute when it resolves.
If the js
block needs to use variables from the surrounding _hyperscript code, these need to be explicitly declared as shown:
<button
_="on click
set text to #input.value
js(me, text)
if ('clipboard' in window.navigator) {
return navigator.clipboard.writeText(text)
.then(() => 'Copied')
.catch(() => me.parentElement.remove(me))
}
end
put message in my.innerHTML "
></button>
end
end
cannot appear inside JS code as an identifier. However, it can appear in string literals ("end", 'end'
, not `end`
).
Here are workarounds for some cases where you might need end
in your JavaScript code:
// Don't:
var end = getTheEnd();
// Do:
var theEnd = getTheEnd();
// Don't:
getEndable().end();
// Do:
getEndable()["end"]();
// Don't:
var template = `this can only end ${good ? "well" : "badly"}`;
// Do:
var template = `this can only ${"end"} ${good ? "well" : "badly"}`;
// Don't:
var regex = /end (.*)/;
// Do:
var regex = new RegExp("end (.*)");