ZIM - Code and Learn Coding with ZIM for JavaScript and HTML Canvas with CreateJS


Practice with ZIM CODE see the Learn Page for tutorials


Lesson 03 - Functions and Events

Creative Coding Videos are above at right - they are a few versions behind the current ZIM.
Differences are that time is now in seconds not milliseconds and ES6 is now used not ES5.


A function is a block of code that we can run whenever we call the function. This lets us put repeated code in one place - which is more efficient and consistent. In this sense, functions help us with abstraction - as we will explore in a future lesson. Functions can also be used to just organize our code.

Below are the ZIM CODE convenience functions, many of which are shared by coders around the world.

In JavaScript, a function is what a class is made from - such as all the ZIM Display Classes we were using the first two lessons. Also, a method is a function stored on a class and run on its object. Here are the ZIM METHODS.

An event is how we handle interactivity. We capture an event when something happens like a mouse click, a keydown, an image load, etc. We can then call a function to do something when the event happens. This is how all the interactive media EXAMPLES work!

Let's take a look at REFERENCE and PRACTICE sections first for functions and then for events!

Function Literals:REFERENCE | PRACTICE


Function ► What IZ Function
A function can be declared with the function keyword followed by the name of the function (the identifier) then round brackets ( ) then squiggly brackets { }. Inside the squiggly brackets is the block of code that executes when the function runs.

function message() {
    // the block of code that will run (indented)
    // can be many statements

The function does not run until it is called (executed). We call the function by using its name (indentifier) and round brackets (). The terms call, run and execute are all the same thing.

function message() {
    // the block of code that will run (indented)
    // can be many statements
message(); // calling the function

A declared function is hoisted to the top of its scope. The scope is the containing function or global if the function is not inside a function. This means that you can call the function before you define it.

message(); // calling the hoisted function
function message() {
    // the block of code that will run (indented)
    // can be many statements

We have seen parameters when making objects from classes or when running methods. So the same applies to functions (as those others are functions).

// zog() is a ZIM function that logs to the console (F12)
// the plus sign (+) means concatenation (join) for Strings
function message(avatar, words) {
    zog(avatar + " says " + words);
message("Dr. Abstract", "Aloha!"); // calling the function

Functions can return a value using the return keyword. Nothing in the function runs after a return. If the function does not return a value then the return value is undefined. The returned value is placed in the code right where the function is called.

function area(width, height) {
    return width * height;
const cost = area(20, 10) * .5;
// the return value of 200 gets multiplied by .5
// so cost is equal to 100
new Label(cost).center();

A function defines the scope of any variables or functions declared within it.

// variables are available within the function they are declared
// they are said to be global if not declared within a function
// usually we avoid setting variables in the global scope
// so that our code does not interfere with other code that may be there

function test() {
    var a = "hi";
    zog(a); // logs to console the word "hi"
zog(a); // error! a is not defined

// in JavaScript 6, we use let instead of var
// let has a scope of any { } in which it is defined
// whereas var has the scope of { } belonging to functions only

let a = 8;
if (a > 7) { // we see conditionals later
    var x = 10;
    let y = 20; // only available inside { }
zog(x); // logs 10 in the console
zog(y); // error! y is not defined


We will use many many functions as we code. Soon, making them will be second nature. Remember that we define (make) functions and then to run them, we must call (execute) the function.

1 Basic Functions Show


Function Literal
In JavaScript, functions are objects made from the Function class. We can also make function literals (anonymous functions or function expressions). These can be assigned to variables or passed as parameters or be treated like any other object. We used to use anonymous functions a lot but in ES6 we turned to Arrow Functions.

const test = function() {
test(); // logs testing! to the console
// the function is NOT hoisted when it is assigned
// so it cannot be called before the assignment

Arrow Functions
Arrow functions were introduced in ES6 and have mostly taken the place of Anonymous functions. They have several forms.

const message = (word) => {
message("hi"); // logs hi to the console

// if there is a single parameter you do not need the ()
const short = word => {return word + ", wonderful";}
short("hi"); // logs hi, wonderful to the console

// if there is a single statement - the value will be returned
const shorter = word => word + ", wonderful";
// put () around an object literal to return an object literal

See the call below where we collect a single target parameter is passed into the {} with => the arrow (two-character) operator.

new Rectangle()
        // set the call property to a function literal
        // animate passes in the target of the animation
        call:target => {

Stage Update
Function literals and Arrow functions are often used in asynchronous cases - that is something that runs later (out of sync). Often when we make changes at a later time, we need to update the stage so the change can be seen. We use the update() method of the stage to do so.

Other asynchronous cases are ZIM timeout() and interval() functions that match JavaScript setTimeout() and setInterval() but in seconds not milliseconds and with more features. These run functions after a certain time - or repetatively after certain times. The ZIM Ticker() lets you run a function at the app framerate (60 fps). Another example is calling a function when an event happens - which we explore in the second part of this lesson.

timeout(1, () => {
    zog("logs after one second;");
    // changes need a stage.update();

interval(1, () => {
    zog("logs each second - like a timer");
    // changes need a stage.update();

interval(1, () => {
    zog("run five times starting right away");
    // changes need a stage.update();
}, 5, true);

Ticker.add(() => {
    zog("very fast");
    // automatically updates!

// note: the videos may have time in milliseconds for the older versions of ZIM.

Let's try out some functions and then we will have a look at events - which call functions.


Arrow Funcitons are used when assigning a function to a variable, a property or passing a function as a parameter.

2 Arrow Functions Show


Events ► What IZ an Event?
We use the on() method to capture events. This is very similar to the traditional JavaScript addEventListener() but shorter - and there are a couple extra features.

Put the object that is receiving the event first, then the on() method with the first parameter being the event type as a String and the second parameter being the function to call when the event happens:

// use the cur() method to add a pointer cursor
// to tell the user that the object is interactive
const circle = new Circle().center().cur();

// do NOT chain the on() method as it does not return the object
circle.on("click", () => {

// adding true as the third parameter runs the event only once
// this is something addEventListener does not have
circle.on("click", () => {
}, null, true);

// use off() to remove an event
// store the event return value to use with off()
const myEvent = circle.on("click", () => {
timeout(5, () => {
    // remove the event after 5 seconds
    // use the same syntax as on
    // but replace the function with the stored reference
    circle.off("click", myEvent);
// Note: if you want to add the event function again
// make sure you re-assign it to the variable myEvent
// use let not const in that case

Types of Events
Not all objects have the same events but here are common events:

Common Events

See the docs for lists of events an object has. These are near the bottom of the description after parameters, methods and properties.

Event Object
The event function is given a single parameter which is an event object. We often collect this as the identifier, e. The event object holds information about the event such as the target, the currentTarget, the keyCode (for keyboard events), etc.

The target is what causes the event. The currentTarget is the object the event is placed on. Often these are the same unless the event is placed on a Container.

const circle = new Circle().center().cur();
const rectangle = new Rectangle().addTo().cur();

circle.on("click", remove);
rectangle.on("click", e => {
    e.target.removeFrom(); // removes what is clicked on

const holder = new Container(stageW, stageH).addTo();
const circle = new Circle().center(holder).cur();
const rectangle = new Rectangle().addTo(holder).cur();

holder.on("click", remove);
function remove(e) {
    e.target.removeFrom(); // removes what is clicked on in the holder
    // e.currentTarget.removeFrom(); // would remove the whole holder

Let's try out events in a PRACTICE section!


Remember that events happen after the original stage.update(). This means that there needs to be another stage.update() inside the event function.

3 Events Show


We have seen examples of types of functions and events. There are more but these are most of the variations. Please practice them a few times. Learning syntax will help reduce problems as you code and let you concentrate on the logic. We look at logic and organization in the next lessons with conditionals, loops, arrays and abstraction.

LESSON 02 - Config Objects and Animation LESSON 04 - Abstraction