Call a JavaScript Function from an HTML Block
Introduction
This Tutorial will show you how to use any EachScape Block Event to trigger a JavaScript function stored in an HTML Block. This is a good way to interact with things inside an HTML block from elsewhere in a view.
We use an Action called 'Call JavaScript Function' to invoke the JavaScript.
To best illustrate how to make JavaScript function calls we created a Tutorial app:
Install 'Call JavaScript Function' app in your workspace.
All Tutorial apps are available in your Dashboard, under Tutorial
Create JavaScript Function
- JavaScript functions are created and stored in HTML Blocks.
- The HTML Block storing the function MUST BE a Custom Block (also called MyBlock).
- We trigger the JS Function using an EachScape Action: Call JavaScript Function
- The EachScape Block triggering the function MUST BE in the SAME VIEW as the HTML Block holding the JS function.
Simple JavaScript Function
We reuse the same the JS function from the previous Tutorial JavaScript in an HTML Block
That function uses a text parameter and displays that text in the HTML Block.
Here is the JavaScript code stored in our HTML Block (Install the Tutorial app in my workspace)
<!DOCTYPE HTML>
<html>
<head>
<script>
function myFunction( myText ) {
document.getElementById("demo").innerHTML = myText;
}
</script>
</head>
<body>
<h1>RESULTS</h1>
<p id="demo">We will insert text typed in here</p>
<!-- This line is from our previous demo:
<button type="button" onclick="myFunction()">Try it</button>
In this new example instead of a JS Button, we use an EachScape Block to trigger the event call the function.
-->
</body>
</html>
Triggering the Function Call JavaScript Function Action
In this example, we use an Input Block to
- Use an Input Text Block to capture text stored in a variable : textInput
- Use the Done Event of the Input Text Block to trigger the 'Call JavaScript Function' action
The variable is passed as a parameter to the JS function.
In this example the JS Function simply displays the text (argument of the function) on screen.
Configuration of the Call JavaScript Function action
Block: The Custom HTML Block (myBlock)
The HTML Block MUST be in the same view as the Block triggering the Function
Function: The name of the function defined in your HTML Block.
Argument: We pass the textInput variable as argument of the JS Function.
Argument for JavaScript MUST be surrounded by quotes "[[var:textInput]]"
You are now able to create a JavaScript in an HTML Block and trigger that JavaScript using an EachScape Event.
Next you can think of accessing iOS and Android native features like GP, Camera with JavaScript.
You can do this by executing an EachScape Script from JavaScript or even writing an EachScape script in JavaScript...
Learn More
- Execute an EachScape Custom Script from an HTML Block
- Write an EachScape Custom Script using JavaScript