Previously

HTML is a tree of elements

Syntax: <tag>...</tag> or <tag>

Tags can have attributes:
<tag attr1="val" attr2="val" ...>

Common tags:
html, body, div, p, a, ul, ol, li, section, nav, table, tr, td...

Cascading Style Sheets (CSS) apply style to elements

Numerous CSS selectors: tag, class, id, ancestry, and some others

h1 { ... }
.checked { background: orange; }
#specialDiv { ... }
#main header .subtitle { ... }

JavaScript & AJAX

JavaScript lets you do what CSS can't

Full-featured programming language with Java syntax

JavaScript (JS) syntax

function mapReduce(fun) {
  var tab = [1, 2, 3, 5.12];
  var sum = 0;
  for (var i = 0; i < tab.length; ++i) {
    if (fun(tab[i]) == true)
      sum += tab[i];
  }
  return sum;
}

Keywords, local variables, operators, and constants

DOM: Document Object Model

HTML elements represented as JS objects

var s = $('section')
s.children[0] == $('header')
s.children[1] == $('p')

DOM traversal with jQuery

CSS-like selector '$'
$('header .sub')
$('section')
$('section').children()
$('a') $('a').closest('section')

'$' returns an array of matching elements

DOM manipulation: Change attributes

Change attributes

$('input').attr('required', true)
$('p').addClass('left')
$('p').text('new text')

...

...

DOM manipulation: Change style

.alert {
  color: red;
  font-weight: bold;
}
$('p').addClass('alert')
    

A header

Some text

Other text

DOM manipulation: Add, remove elements

var li = $('<li>List item #3</li>')
$('ul').append(li)
$('ul li').remove()
    
  • List item #1
  • List item #2

DOM manipulation: Combo

$('.comment')
  .filter(function() {
    return $(this).text() === 'Mario'
  })
  .data('user', 'mario')
  .addClass('highlighted')
  .append("<p>it's a him</p>")

Can chain calls to jQuery functions.
They apply to the currently-selected elements.

DOM events

Respond to user interaction within the page

List of events on MDN

All you need to know about events

Register an event
$('p').on('click', hide)

The callback (or handler) is called whenever the event occurs on any selected element.

Inside the callback, this refers to
the DOM element that raised the event.

Mouse click on element 0 $('button').on('click', ...);

Mouse enters or leaves element 0 $('div').on('mouseenter', ...);
0 $('p').on('mouseleave', ...);

Input element content is changing $('input').on('input', ...); 0

How to include JavaScript in a page?

Using the <script> tag

<script>alert('hello')</script>

From a linked file

<script src="/js/index.js"></script>

AJAX

Asynchronous JavaScript And XML

JSON rather than XML

Asynchronous requests

Concept: send and receive messages in the background

What for?

New page on each response

AJAX allows you to update parts of a webpage in the background

JSON (JavaScript Objet Notation) format

{
  "events": [
    {
      "name": "Event A",
      "begin": "2013-10-18 18:00:00",
      "end": "2013-10-19 6:00:00"
    },
    {
      "name": "Event B",
      "begin": "2013-10-23 18:00:00",
      "end": "2013-10-23 19:00:00"
    }
  ],
  "length": 2
}

AJAX: How do you send a request?

XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/ressource', true);
xhr.overrideMimeType('application/json');
xhr.onreadystatechange = function() {
  if (this.readyState === 4 &&
      this.status === 200) {
    var jsonData = JSON.parse(this.responseText);
    // do something with data
  }
};
xhr.send();

  • XHR is the underlying mechanism
  • Bad name: not tied to XML at all
  • Boolean is for async

Using jQuery:
$.get('/user/Luigi/friends')

$.post('/post/123/comments', '...')

$.ajax({
  type: 'GET',
  url: '/user/Mario/posts',
})

How do you receive the response?

$.get(url, onSuccess);

function onSuccess(data) {
  $('body').append(data)
}

The callback is called when the request succeeds, with optional response data

How do you catch errors?

$.ajax({
  url: '/users',
  success: onSuccess,
  error: onError
})

function onError(req) {
  // Alert user,
  // Retry later, ...
}

The callback is called when the request fails.

What you can do with it

Keep in mind

What I did not tell you

Further reading

Resources

Helpful libraries

FIN