There are no tracking or monitoring cookies on this site. There are only cookies used for documentation examples related to cookies.
Close

Processing...
This may take a few seconds.

JavaScript Expressions

A JavaScript expression is simply the right-hand side of an equation in JavaScript, which in Active CSS needs to equate to a valid JavaScript variable or element.

The syntax for inserting an expression is: {= javascript expression =}.

You can put expressions into an action value, a conditional value, a control flow statement, a component or a target selector.

You can put whatever you like into an expression, as long as it is a valid JavaScript expression.

Eg. if we are working in JavaScript, we might do something like this:

let nowTime = new Date().toLocaleTimeString();

The expression is on the right-hand side. To use the same expression in an Active CSS action value, we simply place it in between "{=" and "}":

render: {= new Date().toLocaleTimeString() =};

You mostly always need to use the outer wrapper {= =} when you need JS expressions. This is so that the core knows when it needs to evaluate raw JavaScript.

However, there are handy exceptions to the rule, and those are when assigning variables and using @if control flow statements. JavaScript expression are written directly and you don't need to use the outer wrapper "{= =}":

$clockTime: new Date().toLocaleTimeString();

...

@if (document.querySelector("div").style.backgroundColor == "green") {

All JavaScript expression variables are run dynamically. So they will be evaluated each time an event is run.

You can mix JavaScript expressions with other parameters and have more than one expression in the same line if you need to, each one using an outer wrapper {= =}.

An unsupported result type will be returned as substituted into the config as the error string "Invalid expression".

Below is a simple example of building an interactive clock using JavaScript that produces a time string that we can use in the render command.

We will be adding more examples as we think of them. If you have any good ones, let us know :)

Basic clock with reactive variable

The Active CSS "draw" event is triggered when any element is first drawn on the page.
When the "clockTime" variable changes every second, it re-draws automatically.
The double curlies around clockTime means "re-draw when the variable changes".
Only the content drawn in variable placeholders is updated, never the whole HTML tag.
(Reactive variables can also be placed inside attributes.)