Lecture Presentation

Lecture Presentation


  • JavaScript Basics
  • Document Load Event
  • Touch Event
  • CSS3 Transitions
  • JavaScript Libraries

JavaScript Basics

  • Course goal is not to teach details about JavaScript
  • The programming language of the web
    • Syntax similar to the C family of languages, like C, C++ and Java
    • Adds dynamic language features that are quite different
  • Statements ends with ;
    • Actually optional, but I recommend always to use it to avoid confusion in some situations

Where to put your JavaScript

  • <script> elements inside the html
  • <script src="other-file.js"> elements
    • Place JavaScript code in separate file. Good for organization. Bad for latency. Note that there is no <script> tag in the ".js" file.
  • Event handler attributes like onclick=""
    <button onclick="doSomething();">
  • Links with protocol javascript:
    <a href="javascript:doSomething();">

JavaScript variables and objects

  • Not a typed language. All variables are typed "var" and can contain any type of value.
  • Declare variables
    • Declared variables are always scoped to the function NOT the { block }
    • Undeclared variables are always global (to the web page)
  • Example
    var num = 123;
    var name = "Mike "+num;
    var length = name.length;
    alert(name.substring(2, 4));

JavaScript conditions and repetitions

  • Selective statements / conditions
    if (number==4) { alert("Hello!"); }
    if (name=="Joanna" && number<5) {
    else {
  • Iterative statements / repetitions
    for (var index = 0; index <10; index++) { alert("Hello!"); }
    while (number>5) {

JavaScript functions

  • Important and versatile feature in JavaScript
  • Example
    function myfunc() { alert("Hello!"); }
    var onefunc = function() { alert("Hello!"); }

Document Object Model

  • Access and manipulate the elements in the web page
  • Predefined object in the DOM
    • document
    • window
  • Set an id for all html elements you want to access
    <h1 id="title">This is my title</h1>
  • Get the object representation of an html element in the web page
    var obj = document.getElementById("title");
    obj.innerHTML = "A new title for the H1 element";

Element manipulation

  • Change the contents of an element (inside the start/end tags)
    obj.innerHTML = "My name is <b>Mike</b>!";
  • Change an attribute of an element
    obj.id = "newUniqueId";
    obj.setAttribute("class", "redline");
  • Change a style property of an element
    obj.style.display = "none";
    obj.style.backgroundColor = "#a055d0";

Element manipulation

  • Create a new element
    var obj = document.createElement("div"); 
  • Add the new element somewhere on the page
    someParentElement.insertBefore(obj, someChildToKeepAfter);
  • Remove an element


  • Things that happen in the web browser
    • The page has finished loading. The user clicks or touches on the screen. The browser window is resized. And many more.
  • Event naming
    • Every event has a unique name like "load" or "click", sometimes the prefix "on" is used depending on the context ("onload" or "onclick" and so on).
  • You create a handler as a function in JavaScript
    • When the event happens, your function is called with an event object containing more information about the event (if relevant).
  • Default handlers
    • Many events have default handlers in the browser that can be prevented from executing, if wanted.

Catch an event with a handler

  • In an attribute of an html element
    <h1 onclick="doSomething();">
  • By setting the element property
    obj.onclick = doSomething;
  • By calling addEventListener for the element
    obj.addEventListener("click", doSomething, false);
  • Actually, Internet Explorer is different
    obj.attachEvent("onclick", doSomething);

Anonymous functions

  • Often used as event handlers
  • A function with no name must be used at the same time as it is defined
  • Example
    obj.addEventListener("click", function(eventinfo) {
      alert("Got a click in the app!");
    }, false);

Event object

  • First argument to the handler function
  • Variable named event in html attribute
  • Internet Explorer stores it in window.event (NOT sent as argument)
  • Information depends on the type of event
    • target is always the element that caused the event to fire
    • keydown has code of key pressed
    • mousedown has position of mouse
    • touchstart has position of touch
  • Example that is browser independant
    function whenEventHappens(evinfo) {
      evinfo = evinfo ? evinfo : window.event;
      alert("Got event on an element of tag " + evinfo.target.tagName);

Load event

  • Fired when the web page has loaded all content
  • Important not to manipulate elements too early (before they exist)
    • Don't do anything until inside the load event handler
    • Or place the JavaScript code in a script element at the end of the body
  • Ways to catch
    • In the body element using an attribute
      <body onload="doIt();">
    • Set the window property
      window.onload = doIt;
    • Add function to window object
      window.addEventListener("load", doIt, false);
    • And remember you can use an anonymous function instead of doIt

Default event processing

  • Prevent the default action after your event handler has been called
  • Events will bubble up
    • The event is always first dispatched to the element where the event happened. Then the event is dispatched to the parent element and this continuous up until the topmost element the window (for most events).
  • Strategy
    • Instead of catching events on a lot of elements, one strategy can be to catch events on a parent element and then check event information for which particular element actually fired the event.
  • Prevent bubbling of events
    evinfo.cancelBubble = true;

Mouse events

  • These events will to some extent be simulated on touch enabled devices, even though they have no mouse support
    • Since you are aware of mobile devices, it is usually best NOT to rely on simulated events and instead catch and implement handlers for the actual touch events.
  • mousedown
    • When mouse button is pressed. Event info will have information about which mouse button.
  • mousemove
    • Whenever the mouse is moved over an element
  • mouseup
    • When mouse button is released. Note that this event might not fire if the mouse is released outside of the element.
  • mouseover (mouseenter is similar)
    • When the mouse pointer first enters the inside of an element. Use for "hover" effects.
  • mouseout (mouseleave is similar)
    • When the mouse pointer is moved outside of an element after previously being inside.

Touch events

  • Never fired on desktop browsers (not supporting touch)
  • touchstart
    • When finger is first pressed on the screen
  • touchmove
    • When finger is moved while pressed on the screen
  • touchend
    • When finger is released from the screen

Touch event information

  • evinfo.touches
    • An array of all fingers currently on the screen
  • evinfo.changedTouches
    • An array of only the fingers that changed since the last touch event was fired
  • evinfo.targetTouches
    • An array of only the fingers that are pressed on the element that fired the event
  • Each item in the array has additional properties
    • pageX has horizontal screen position of touch
    • pageY has vertical screen position of touch
    • Example
      var x = evinfo.touches[0].pageX;
      var y = evinfo.touches[0].pageY;

Pattern for supporting both mouse and touch with common code

  • Catch both events
    if (window.attachEvent) {
      obj.attachEvent("ontouchstart", onDown);
      obj.attachEvent("onmousedown", onDown);
    else {
      obj.addEventListener("touchstart", onDown, false);
      obj.addEventListener("mousedown", onDown, false);
  • Handle different places for coordinate in event handler
    function onDown(evinfo) {
      evinfo = evinfo ? evinfo : window.event;
      var x = evinfo.touches ? evinfo.touches[0].pageX : evinfo.pageX;
      var y = evinfo.touches ? evinfo.touches[0].pageY : evinfo.pageY;

CSS3 Transitions

  • A way to create animations on a web page when changing style properties
    • Transition changes one or more style properties in intermediate steps over a definied period of time
    • Transitionable styles
      • Colors, like "color", "background-color"
      • Shadows, like "box-shadow" and "text-shadow"
      • Position, like "left" and "top" for elements with absolute position
      • Transforms, like "scale" and "rotate"
      • And more. On or off styles are not transitionable (for obviuos reasons), like "display"

Steps to use CSS3 transitions

  • Define a start value for the style to transition
    .headline { background-color: #000; }
  • Define that a transition should occur for this element when a change happens
    .headline { -webkit-transition: background-color 2s; }
  • Change the style property
    obj.style.backgroundColor = "#fff";

JavaScript debugging

  • You will most certainly make errors in your JavaScript code
    • Errors are silent on mobile devices (and often also on desktop browsers)
  • Syntax errors
    • You've typed something wrong in your code. All JavaScript interpretation will stop at the error.
  • Runtime errors
    • Your code is typed correctly, but some other error occurs when the code runs (like trying to use a null object reference)

Strategies to discover errors

  • alerts
    • Create alert()-calls in your code to verify that you reach a certain point and/or show values of variables and object properties.
    • Example
      alert("Point reached with display set to: " + obj.style.display);
  • Catch all errors in your own code
    • Catch the error event for the window object and show the error to yourself or take other action. Assumes that JavaScript at least reaches the code point at which the event is caught.
    • Example
      window.onerror = function(event) {
        alert("Oops!\n" + event.message);
  • Use Chrome Developer Tools
  • Use other Remote Debugging Tool