The js Command (inline)

Note: This page is about the inline JS command. _hyperscript also supports JS blocks at the top level.

The js command lets you embed JavaScript code directly in your hyperscript. The return value of the JS block becomes it for the next command. If the block returns a promise, the following hyperscript code will wait for it to resolve.

this inside a js block is the global scope (window, or self in workers).

Passing Variables

If your JS block needs to use variables from the surrounding hyperscript, you must explicitly declare them in a parameter list:

<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>

Examples

<button
  _="on click
           js
               if ('clipboard' in window.navigator) {
               	 return navigator.clipboard.readText()
               }
           end
           put it in my.innerHTML "
></button>

Note on 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 (.*)");

Syntax

js [(<param-list>)] <js-body> end