javascript and jquery - home | course web pages | jack baskin
TRANSCRIPT
Javascript and jQuery
CMPS 193, October 18
Javascript
Main features:● Scripting language = interpreted● Can interact with the DOM of a web page: DOM =
Document Object Model, a tree model of the logical structure of the web page (document).
● Powerful way of interacting with events.● Uses continuations to handle event-driven programming
(we'll see that).
In general, a web page is becoming a vehicle for delivering applications, and javascript is the most universal way in which to code such applications. With javascript, a page becomes a program, which can communicate at will with the server. Think of Gmail.
Including javascript
Via tags:
<script type="text/javascript">var x = 1;var y = x + 1;</script>
Via inclusions:
<script type="text/javascript" src="url"></script>
Language structureDeclaring variables:
var x = 1;var y = "Hello";
Types: the usual assortment,● "strings" and 'strings' (same meaning)● integers, floats● Boolean: true, false● null (like None in Python)
Constants:const TEN = 10;
Oh, note the semicolons!;
Arrays
var a = new Array();var a = [];
a[0] = "cat";a[1] = "dog";
Methods: ● b = a.pop(); // Removes and returns last element● b = a.shift(); // Removes and returns first element● a.push("canary"); // Adds to the end ● a.sort(f); // f is a comparator function.● a.length // length of a.
Dictionaries
var d = {}d['dog'] = 3;d['cat'] = 4;
d.length? 0
What's going on? Well, we are adding properties with values to the array object d. But never mind, it works (mostly) like a dictionary.
var d = {'dog': 3, 'cat: 4};is also valid.
d['helen'] == null // this is true
Statements
if (a == 3) { ... } else { ... }
for (i = 0; i < 10; i++) { document.write(i); }
while (condition) { ... } // the break statement works in loops
do { ... } while (condition);
Functions
function addup(a, b, c) { return (a + b + c);}
// Functions can also be declared in lambda-notation:
f = function (x) { return (x * x); }
Ok, so what's the fun?
The fun is to interact with the page DOM (document object model).
Browsers internally represent a page via its parse tree, and javascript can:
● Manipulate this parse tree (add / remove subtrees, add attributes to nodes, ...)
● Catch events, and rely them to javascript. ● Cause browser to server communication.
Problem: every browser offers slightly different DOM models, etc. Solution (99%): use the jQuery library.
JSON
JSON (Javascript Object Notation) is a way to serialize into a string a Javascript object: array, dictionary, string, number, whatever. JSON is portable across languages (Python, PHP, etc, have libraries to decode / encode JSON).
Once upon a time, the idea was that XML was an universal language in which to encode data passed between web services (or between browser and server). But:
● XML is verbose● XML parsers are complex, and ... cumbersome (they
require a dom definition, yada yada)JSON is what is now universally used (except perhaps to encode HTML itself).
JSON in action
> var contact = { "Name": "John Doe", "PermissionToCall": true, "PhoneNumbers": [ { "Location": "Home", "Number": "555-555-1234" }, { "Location": "Work", "Number": "555-555-9999 Ext. 123" } ] };> JSON.stringify(contact);"{"Name":"John Doe","PermissionToCall":true,"PhoneNumbers":[{"Location":"Home","Number":"555-555-1234"},{"Location":"Work","Number":"555-555-9999 Ext. 123"}]}"
Using JSONBest for compatibility: include the json2.min.js library; see www.json.org for this library.
Then, use
● JSON.stringify(obj);● JSON.parse(string);
Every language then has its libraries, on the server side; see again www.json.org. In Python, there are:
● simplejson● json library as part of the standard library.
JSON vs. XML XML JSONScalars types No. Oh, and good luck with < >
escaping, or is that < >Yes. Strings, integers, floats have native meaning.
Arrays, objects No. You need to invent a translation.
Yes.
Null No. Need to use xsi:nil element plus importing a namespace...
Yes, 'null'.
Namespaces Yes No, but who cares?
Parsing Complicated... Great simple libraries.
Learning curve Easy, just learn XPath, XML Schemas, XSLT, XML namespaces, DOM, ...
Easy, really.
Luca's personal opinion: XML is the typical overcomplex overbrainy solution, which fails in practice. In practice, programmers need simple, effective, flexible solutions. JSON is the way to go.
Javascript and DOM
DOM: A tree representing the document.Install FireBug on Firefox, and look at it.
Every node has: ● nodeName● attributes● childNodes (an array)● firstChild, lastChild, nextSibling, parentNode● nodeValue
Oh, and it's slightly different across browsers.
jQueryjQuery is a Javascript library that:
● Is cross-browser● Makes it easy to interface to DOM● Makes it easy to send/receive data to browser (AJAX)
Comes with:● jQuery UI: A set of UI extensions that makes it easy to do
animations, tabs, accordions, and more.● CSS editor.
jQuery is becoming the default; my advice is: develop for it.
jQuery
jQuery defines an object, $, that does magic for you.
Selectors: One of the basic problems is, "give me a certain DOM element".
<div class="blog_post">My blog post</div>
$(".blog_post") // class selector
<div id="result"></div>
$("#result").html("This is the result"); // id selector
$("div") // element selector
jQuery: simple examples
$("a").addClass("test");$("a").click(function(event){ event.preventDefault(); $(this).hide("slow"); });
jQuery: Events.click(), .hover(), .keypress(), .keyup(), .keydown(), ...: These functions attach event handlers to elements.$('a').click(function(el) { el.preventDefault();alert('Ouch!');});
Useful:
$(document).ready(function() {...});
Writing to the DOM
$(selector).html("Luca was here");
AJAXPOST:
$.post('someurl', function(data) { ...});
$.post('someurl', {'cat': 3, 'mouse': 'Jerry'}, function(data) { ...});
AJAX
GET
$.get
Example: get the content of "hello.html" and write it in a div:
<div id="result"></div><script>$.get("hello.html", function(data){ $("#result").html(data);});</script>