1 of 51

Javascript

Bring things to live

Pili Hu

e@hupili.net

2 of 51

Week 4 Theory (Cont’d)

3 of 51

Playground Services

Examples:

https://jsfiddle.net/

http://codepen.io/pen/

http://codepen.io/patterns -- A collection of code snippets for design patterns

  • What you see is what you get
  • Web-based; easy to share with others
  • Reproducible

4 of 51

How to ask questions

  • Principle:
    • Do your best effort search & research first
  • Format of asking:
  • Describe problem clearly
    • What you want to achieve, rather than the fact that your method does not work
  • Create a Minimal, Complete, and Verifiable example (more)
    • The playground services will help

Ref:

http://stackoverflow.com/help/how-to-ask

5 of 51

[important] A code generation trick

Use spreadsheet to save duplicated work:

https://docs.google.com/spreadsheets/d/1vCnb_-W0T6F8iSkZGH0VdiqbM7-ICq0ZGzhAFslNobI/edit#gid=0

(Can use javascript to save duplicated work in the future)

6 of 51

Concept Review

7 of 51

How it all fit together?

8 of 51

HTML: Element

Light

Mirror

Glass

Engine

Wheel

9 of 51

CSS: Style

Shell: Blue;

Light: White;

Size: 4.9m X 1.9m X 1.4m;

Glass: Transparent;

...

10 of 51

JS: Control

Light:

on/off

Engine:

start/ stop/ speed up/ speed down

Wheel:

turn

left/ right

11 of 51

Paired and nested tags

html, head, body, h1, h2, p, b, i, ul, ol, li, img

...

12 of 51

Different element → different key

Different key → different value set

Selector

Key:Value;

13 of 51

Can manipulate HTML/CSS

Context matters

Can only touch the surface here

document.getElementById('myp').style='background-color:lightgrey;color: green;'

document.getElementById('myp').innerHTML = '<ul><li>item1</li><li>item2</li></ul>'

Result

JS

14 of 51

The missing pieces:

  • Basic calculation
  • Basic data structure: list, dict
  • Object/ method/ function
  • Control logic:
    • block, condition, loop
      • (more on this when used)

15 of 51

Javascript

16 of 51

Basic Operations

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math

  • Arithmetic: +, -, *, /, %
    • Result is a number
  • Comparison: ===, !==, <, >, <=, >=
    • Result is a boolean value (true/ false)

17 of 51

Math operation with variables

  • “var” notation
    • Most of the time, it is good to use “var”

18 of 51

Data Types

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables

  • Number
  • String
  • Array: []
    • Sometimes called List
  • Object: {}
    • Sometimes called Dict (dictionary)

19 of 51

Use Functions

Syntax: object.function(arg1, arg2, ...)

alert("Hello World")

window.alert("Hello World")

Tip: Learning Javascript libraries are mainly about learning what are the available objects, available functions and how to use them. -- Object Oriented Programming

20 of 51

String and String operations

  • Most widely used data type
  • String is a sequence of characters
    • Can be escape characters, Ref
    • Can be treated as an array ( [] ) of characters
  • A lot of string functions
    • substr -- get substring
    • replace -- useful for template filling

21 of 51

Commonly used objects

  • window
  • window.document
    • i.e. document
  • console
    • console.log
  • Date
    • .now()
    • .getMonth()/ .getHours()/ …
  • Math
    • .sin()/ .cos()/ ...

Note: Date.now() gives a “unixtimestamp”, see here what it is: http://www.unixtimestamp.com/

22 of 51

DOM Object

  • Every HTML tag/ element corresponds to a DOM Object
  • Manipulating DOM object is the foundation for interaction
  • Common method/ attribute:
    • Access object:
      • .getElementById(), .getElementByXXX(), ….
        • The returned value is also DOM object, i.e. you can access child in the same way
    • Content:
      • .innerHTML, .innerText
    • Navigate DOM tree:
      • .parentNode, .childNodes
  • Find a list here: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

23 of 51

Javascript in the Console

  • Arithmetics
  • Variables
  • Data structure
    • []
    • {}
  • Functions

24 of 51

New Object

d = new Date()

d.getMonth()

d.getHours()

Further reading:

http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript

It can be confusing for the “new” operation. Sometimes you need to use “new”. Sometimes you call the function directly. Just follow documentation or samples at this stage.

25 of 51

Define function

function(arg1, arg2, ...){

// Your code blocks here

return … // return value

}

  • Function helps to better organise codes
  • Improve code reusability
  • Returning a value can break the execution at any time

26 of 51

Control flow

Control flow determines the order of code execution.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements

  • Block
  • Branch
    • if...else
  • Loop
    • for
    • for … in
    • while

27 of 51

if...else

28 of 51

for

29 of 51

for...in

30 of 51

Integrated Exercise for Javascript

Topic:

  • Control by time
  • Loop to save duplicate work

Sample page:

31 of 51

jQuery

This part is postponed to next week. The slides are here for completeness. You may search the terms/ pointers mentioned in the slides if interested.

32 of 51

Background of jQuery

  • To unify the behaviour across browsers.
  • Not an advantage with HTML5 APIs
  • Still the highest market share in terms of “framework”

33 of 51

Key concepts

  • Get element by CSS Selector
  • Imperative way to modify elements, in a batch
  • Callback:
    • Event listener in function style, e.g. .click
    • AJAX
      • (next week)
  • Many UI components (plugins)
    • (next week)

34 of 51

Example 1: Make a calculator

35 of 51

Example 1 breakdown

  • UI layout
  • Assign “id” to access the element easier

36 of 51

Example 1 breakdown

Any codes here. This code block is executed after all HTML elements are loaded on this page. For now, just follow this common practice.

37 of 51

Example 1 breakdown

  • .click set the event listener to the enclosed function.
    • I.e. that function is executed when the user click the element
  • Common event listener:
    • .click, .dblclick, .focus, .hover, .keypress, .mousedown, …
  • Full list here: https://api.jquery.com/category/events/

38 of 51

Example 1 breakdown

  • .val reads or writes the “value” property of an element
  • Convention of content operation:
    • .operation() -- reads the content
    • .operation(newContent) -- writes the content to be newContent
  • Similar operations:
    • .data, .html, .text, ...

39 of 51

Example 2: Toggle style

40 of 51

Example 2: Toggle style - Key points

  • .hide()/.show() applies on a batch of elements
  • Common trick for interaction:
    • Define the CSS class of state1 and state2
    • Toggle state by .addClass and .removeClass

41 of 51

Example 3: A moving bar chart

  • Learn from comments. “// ….”

https://hkbu-jour2106.github.io/week5-sample/jquery.html

42 of 51

Homework 4

Topic (template) for selection:

Logistics:

  • Apply another data set than what used in the above samples
  • Submit at xxx.github.io/homework4
  • Deadline: N.A.

Tech requirements:

  • Use bootstrap
  • Use jQuery

This part is postponed to next week. The slides are here for completeness. You may search the terms/ pointers mentioned in the slides if interested.

43 of 51

Guest Lecture

44 of 51

Cédric Sam - Interactive Graphics Journalist

Cédric Sam will visit the campus of HKBU and share with the audience a few hand-picked interactive web stories during the talk and outline the end-to-end workflow that takes those stories to life.

I work at Bloomberg News (Graphics) since December 2015. Previously, I worked at the South China Morning

Post (2013-15), La Presse (2013), JMSC HKU (2010-2012) and CBC/Radio-Canada (2007-09). Proud Montrealer

now living in New York City, after seven years in Hong Kong. [Electric Rice Cooker Tumblr | @cedricsam]

http://cedric.sam.name/

Slides:

45 of 51

Common Questions

46 of 51

Chrome Developer Console

The JavaScript Console provides two primary functions for developers testing web pages and applications. It is a place to:

  1. Log diagnostic information in the development process.
  2. A shell prompt which can be used to interact with the document and DevTools.

Reference: https://developer.chrome.com/devtools#console

47 of 51

Java v.s. Javascript

Basically, They have NO RELATIONSHIP at all!!

Two almost totally unrelated languages. JavaScript was named this way mostly because of marketing reasons: at the time, Java was the new cool kid in town, so Netscape (Netscape had lots of weight to throw around at the time) named their scripting language "JavaScript" mostly to get up on the bandwagon.

Reference:https://www.quora.com/JavaScript-vs-Java

48 of 51

Screenshots of lecture demo �(Chrome Developer Console)

49 of 51

Screenshots of lecture demo �(Chrome Developer Console)

50 of 51

Screenshots of lecture demo �(Chrome Developer Console)

51 of 51

Screenshots of lecture demo �(Chrome Developer Console)