Adding JavaScript code in an event sheet
As an easy way to get started, let's write our first line of code in an event sheet. First open the Construct editor and create a new empty project, making sure Start with is set to Event sheet.
Then click the Event sheet 1 tab to switch to the event sheet view.
Now add an On start of layout event:
- Click Add event in the event sheet tab
- Double-click System
- Double-click On start of layout (in the Start & end group)
You should end up with this:
This is an event block that will run its actions on startup.
We can add some JavaScript code in the place of an action in this event block, so our code runs on startup. Click Add... to the right of the block, and select Add script.
A text field appears as an action. This is a small script editor where you can enter some JavaScript code to run.
For now, let's just copy-and-paste in the following line of code in to that text field:
console.log("Hello world!");
Note if you switch away to a different window, the script editor may finish and change in to an empty code block. If that happens, double-click the empty code block to edit it again, and then paste in or copy out the code sample above. Then click outside the script editor, or press Ctrl + Enter, to close the script editor.
You should now see your first line of JavaScript code in the event sheet!
This line of code will log the message Hello world! to the browser console on startup. We'll find how to see that message shortly. To help get you started quickly we're not going to fully explain every part of this code just yet - this guide will go in to detail on it later on. For now though here is a brief summary of what this line of code means:
console.log
means "access the log
function on the console
object"
- The parenthesis
(
and )
mean "call the log
function"
"Hello world!"
is some text, provided inside double-quotes, that is passed to the log
function.
- The semicolon
;
at the end marks the end of a statement
The end result means "add a message with the text Hello world! to the console". Let's find out how to see our message!