invoke
Method
Call any method or function on the client.
Interact with the DOM
A basic alert is a good example to start with.
The
receiver
of the method call is window
when unspecified.
<%= turbo_stream.invoke "alert", args: ["Hello from TurboBoost Streams!"] %>
Delay invocation
We can also delay invocation.
The
delay
should be specified in milliseconds.
<%= turbo_stream.invoke "alert", args: ["Hello from TurboBoost Streams with a delay!"], delay: 2000 %>
Use a CSS Selector
We can invoke methods on an element when using a selector... and pass complex arguments.
The
receiver
of the method call is the selected element
(s) when a selector is present.
<%= turbo_stream.invoke "animate",
args: [
[
{ transform: 'rotate(0) scale(1)' },
{ transform: 'rotate(360deg) scale(0)' }
],
{
duration: 2000,
iterations: 1,
},
],
selector: "#code-animate.highlight" # <- accepts any CSS selector
%>
Select Multiple Elements
We can invoke methods on multiple elements when using a selector.
Dot notation can be used to specify a
receiver
defined on the selected elements.
<%= turbo_stream
.invoke("classList.remove",
args: %w[bg-gradient-to-br dark:focus:ring-pink-800 focus:ring-pink-200 from-pink-500 to-orange-400],
selector: "button[type=submit]") # <- matches all submit buttons
.invoke("classList.add",
args: %w[bg-gradient-to-r dark:focus:ring-cyan-800 focus:ring-cyan-300 from-cyan-500 to-blue-500],
selector: "button[type=submit]") # <- matches all submit buttons
%>
Update the JavaScript Console
We can also interact with the JavaScript console.
Dot notation can be used to specify a
receiver
defined on window
when a selector is unspecified.
Open the JavaScript console to see this in action.
<%= turbo_stream
.invoke("console.clear")
.invoke("console.log",
args: ["DOT notation...", "Logging...", SecureRandom.alphanumeric(8)])
%>