Lecture 7

 

slides.com/jkohlin/js-dom2/

Functions REVISITED

scope perspective

function algorithm(number) {
    var triple = number * 3;
    alert( triple );
}
// triple and number are undefined out here

algorithm is a global variable

number is a local parameter that doesn't need a declaration

triple is a local (scoped) variable because it is declared inside the function

FUNCTIONS REVISITED

declaring PERSPECTIVE

var twice = more(4) // 8

function more(number) {
    var double = number * 2;
    return double;
}
var half  = less(12) // error less is not a function

var less = function(number) {
    var pointFive = number/2;
    return pointFive;
}

Why? 

FUNCTIONS REVISITED

hoisting PERSPECTIVE

var half  = less(12) // error less is not a function

var less;
var half  = less(12) // error less is not a function

var less = function(number) {
    var pointFive = number/2;
    return pointFive;
};
var half;

var less;

Because of the two step compiling process, less is not yet a function when it's being called, it's just undefined so far

Step 1

Step 2

Step 3

FUNCTIONS REVISITED

declaring PERSPECTIVE

var twice = more(4) // 8

function more(number) {
    var double = number * 2;
    return double;
}
var half  = less(12) // error less is not a function

var less = function(number) {
    var pointFive = number/2;
    return pointFive;
}

Functions

exercise

Together with your neighbour,

Write an algorithm in pseudo code on a piece of paper

Instruct me what to do on the whiteboard.

4 - 6 statements

Give it a name on the back of the paper

 

Limited set of options (see next slide):

  • choose a pen color,
  • if this is true, else
  • rotate 15° 
  • repeat
  • draw a shape

Functions

exercise

shapes

 

 

colors

 

 

15° rotation

 

 

Loops & conditions

1 2 3 4 5 6

FUNCTIONS REVISITED

passing parameters

function add(num1, num2) {
    return num1 + num2;
}

alert( add(35, 7) );
function calculate(operator, num1, num2) {
    if (operator == "+") {
        return num1+ num2;
    else if (operator == "-") {
        return num1 - num2;
    }
}

alert( calculate("+", 35, 7) )

FUNCTIONS REVISITED

passing parameters

function draw(color, shape, angle) {
    var pen = new WhiteboardPen()
    pen.color = color;
    pen.rotation = angle;
    pen.draw(pen.color, shape);
}

Functions

exercise

Together with your neighbour,

  • Write a function in pseudo code on a piece of paper
  • Instruct me what to do on the whiteboard.

Use parameters to decide Shape, Color, Rotation

Max 10 statements

  • Fold the paper 
  • Write the function-name on the back
  • Switch paper with the group above/below you
  • Write values after the function name

in that order

FUNCTIONS REVISITED

functions as values

function calculate(operator, num1, num2) {
    if (num1 == undefined || num2 == undefined || operator == undefined) {
        return "Could not calculate. Missing operands";
    }
    if (operator == "+") {
        return num1 + num2;
    else if (operator == "-") {
        return num1 - num2;
    }
}

var math = calculate();       // math is now "Could not calculate. Missing operands"
var math = calculate;         // math and calculate now contain the same function.
var diff = math("-", 45, 3);  // evaluates to 42
var calculator = {
    plus:  function (a, b) { calculate("+", a, b) },
    minus: function (a, b) { calculate("-", a, b) }
} 

FUNCTIONS REVISITED

passing functions as parameters

function draw(color, shape, callback) {
    var pen = {}
    pen.color = color;
    pen.shape = shape;
    callback(pen)
}

draw ( "red", "–", function(p){ 
    if (p.color == "red") { 
        rotate(p.shape, 45deg); 
    }
} ) ; 

Functions

exercise

1's (write f1 on the back)

  • Write a "fantasy" function on a piece of paper
  • Use one parameter called ingredientsObject
  • Write instructions to write on the whiteboard using ingredientsObject's props

2's (write f2 on the back)

  • Write a "fantasy" function on a piece of paper
  • Use parameters for pShape, pColor, pCallback
  • Run the callback, passing an object containing shape, color, loops and a person's name e.g pCallback( {shape:pShape, color:pColor, 3, "Jane"} )

3's

  • Collect the two function sheets, decide on values to call f2 with.
    Use f1 as the callback argument.

Events

when that happens, do this

These events can happen

Form Events Description
reset when the form is reset
submit when the form is submitted
change when the form element changes
select when the element is selected
blur when the element loses focus
focus  when the element gets focus
input when something is typed in an input box
Keyboard Events Description
keydown when a key is pressed
keyup when a key is released
keypress when a key except Shift, ctrl/cmd.. is pressed
Document Event Description
DOMContentLoaded when the HTML document has been completely loaded and parsed
load when the DOM is loaded but not parsed
Mouse Events Description
mouseenter     when the mouse is moved onto the element
mouseover     when the mouse is moved onto the element
mousemove     when the mouse is moved over an element
mousedown     when the mouse button (ANY button) is pressed on an element.
mouseup     when the mouse button (ANY button) is released over an element.
click     when the mouse button (ANY button) has been pressed and released on an element.
dblclick     when the mouse button is clicked twice on an element.
contextmenu     when the right button of the mouse is clicked
wheel  when the mouse wheel is rotated in any direction.
mouseleave     when the mouse is moved off the element
mouseout     when the mouse is moved off the element
select     when text is being selected.

event listeners

add an event listener to an element

PUSH

var button = document.querySelector('button');

button.addEventListener('click', callback);

/* a callback is a function that is to be 
   called when the event happens */

The event object

Contains information about what just happened

PUSH

var button = document.querySelector('button');

button.addEventListener('click', logMe);

function logMe(event) {
    console.log(event)
}

function addEventListener(eventType, callback) {
    //var t = eventType.caller('mumbojumbocode')  
    var e = { target: t, preventDefault: function(){} };
    callback(e);
}

The event object

var event = {
    clientX: 94,
    clientY: 56,
    target: "<li>",
    timeStamp: 1519786715062,
    type: "click",
    preventDefault: function() {
        //don't behave like you normally do.
    }
}
property / method description
currentTarget the object the eventListener was added to
target the object that dispatched* the event
timeStamp when the event happened
preventDefault function: stops default behaviour from happening

*Often the thing you clicked

Forms

input types values and submission

<form action="">
  <input type="text" value="">
  <input type="tel" value="">
  <input type="submit" value="Send">
</form>
document.forms[0].addEventListener("submit", holdIt); 

/* inside addEventListener, an object called event is available
   it contains properties and methods about the actual event */

function holdIt(event) {
    event.preventDefault(); 
    // stops the submit event (page reloading)

    event.target.style.display = "none"; 
    // target is the element that fired the event

    event.target.removeEventListener("submit", holdIt); 
    // removeEventListener will remove an event listener

    alert(document.querySelector("input[type=text]").value);
}

Events, Callback functions and Forms

By Johan Kohlin

Events, Callback functions and Forms

  • 1,369