JavaScript & AJAX
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...
- Points lost on unclosed tags (mind the slash)
- Two types: read doc to find which apply
- Attributes syntax matters
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 lets you do what CSS can't
- Traverse & manipulate the DOM
- React to user actions via events
- Communicate asynchronously with a server or peers
- Combine all of the above
Full-featured programming language with Java syntax
- + sound, webcam, 2d/3d, geolocation, ...
- Explain DOM
- Asynchronous is for next lecture
- Show example
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
- Clown code
- Operators "do" something, dot is for property access
- Arrays not homogeneous, mutable variables
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
- Explain Zepto/jQuery need
- Switch to example in Chrome
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
- Mouse click, double click, right-click, ...
- Text input changes
- Window resize
- Going fullscreen
- Ajax events
- ...
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.
- Callback is any function
- It receives an event object as first argument
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?
- non-blocking interaction
- minimize bandwidth usage
- Browser block by default
- JSON smaller than HTML
- Search is AJAX
- Refresh is AJAX
- Clicks on left menu is AJAX
New page on each response
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
}
- It's just JavaScript! (with quotes)
- Object, Arrays, Strings, Numbers, Booleans
- Can use XML, but JSON simpler
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
- Auto-refresh of data on index page
- Background processing of forms
Keep in mind
- Every user action can happen in the background
- Preserve a smooth user experience
- Look at examples (Github, GMail, GMaps, ...)
What I did not tell you
Further reading
- What happens if the request fails?
- Screen readers, breaking usability patterns
Resources
Helpful libraries
- Libraries for easier traversal/manipulation
- Frameworks are best for large apps
- jQuery doc is on devdoc (slow site)