Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Advanced JavaScript dates JavaScript timing events JavaScript - - PowerPoint PPT Presentation
Advanced JavaScript dates JavaScript timing events JavaScript - - PowerPoint PPT Presentation
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript Advanced JavaScript dates JavaScript timing events JavaScript Lars Larsson cookies Graceful degradation AJAX Summary Lecture #11 Advanced JavaScript 1
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
1 JavaScript strings 2 JavaScript dates 3 JavaScript timing events 4 JavaScript cookies 5 Graceful degradation 6 AJAX 7 Summary
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript strings
We have used strings during these lectures, but not covered some of the more advanced functionality. For upcoming examples and in general, the following are of interest:
- string1.length — returns the length of string1 (just like
an Array)
- string1.indexOf(string2, startPos?) — returns the
index of the first occurrence of string2 in string1 starting from startPos, or -1 if string2 is not part of string1 (startPos may be omitted, hence the question mark)
- string1.substr(start, length) — returns the substring
starting at index start with the given length The entire set of methods can be found here:
http://developer.mozilla.org/en/docs/Core JavaScript 1.5 Reference:Global Objects:String
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
String examples
var s = "Hello world!"; alert(s.length); // 12 alert(s.indexOf("wor")); // 6 alert(s.indexOf("abc")); // -1 alert(s.substr(3, 4)); // lo w alert(s.substr(3, 400)); // lo world!
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript dates
Dates are represented by Date objects in JavaScript. Internally, they keep track of the number of milliseconds since midnight of January 1, 1970. We use a set of methods like the following to manipulate dates:
- get{Hours,Minutes,Seconds,Milliseconds}() — in local
time, returns the hour (0–23), minute (0–59), second (0–59), or millisecond (0–999), respectively
- getYear()/getMonth()/getDate() — in local time,
returns the year (browser dependent representation), the month (0–11), and the day (1–31), respectively
- getFullYear() — returns the year in four–digit notation
- getTime() — returns the number of milliseconds since
midnight January 1, 1970
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript dates continued
There are set–versions of all these as well, that take the suitable parameter (so, setFullYear() takes a parameter like 2008). Additionally, there are UTC (Universal Time Coordinated) versions of both the get– and set–versions of the functions. Simply add UTC to the name, right after get/set (so setDate() becomes setUTCDate()).
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript dates continued
Dates can be represented as strings, and can be parsed from strings as well. A Date object can be represented as a string in the following ways:
- someDate.toString() — returns a String including time
zone information and offset from Greenwich mean time
- someDate.toLocaleString() — returns a String
containing the local time and date formatted according to the visitor’s locale (country) settings
- someDate.toUTCString() — returns a String containing
the UTC time and date formatted according to the visitor’s locale settings
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript dates
To obtain today’s local date and time, we simply create a new Date object: var rightNow = new Date(); We can supply parameters to the Date constructor as well, to initialise the object to some other point in time. Read the full specification here:
http://developer.mozilla.org/en/docs/Core JavaScript 1.5 Reference:Global Objects:Date
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Date example
var rightNow = new Date(); rightNow.setMinutes(40); alert(rightNow.getSeconds()); alert(rightNow.getHours() - rightNow.getUTCHours()); alert(rightNow.toLocaleString());
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript timing events
For timed events (such as, “run the following code in X milliseconds”), JavaScript offers two functions:
- setTimeout(func, delay, param1?, param2?, ...) —
calls the function func after delay milliseconds with the given (optional) function parameters
- setInterval(func, delay, param1?, param2?, ...) —
repeatedly calls the function func after delay milliseconds with the given (optional) function parameters The return values of these calls are IDs for timers that we can cancel, using the appropriate function:
- clearTimeout(timeoutID) — cancels the given timeout
- clearInterval(intervalID — cancels the given interval
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Example
Let us see these functions in an example! Open example-timers.xhtml and see what it does and study the code.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Note on timers
Note that we may run into problems if we overwrite the timeout or interval ID — if it is overwritten, there is no easy way of getting it back. The example featured a “safe” interval and an unsafe timeout. Consider the following: interval = setInterval(...) interval = setInterval(...) clearInterval(interval); Only the second interval is cleared in this case — the first one is still active. This may not be what we intended.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
JavaScript cookies
Due to a design decision, web servers do not keep track of its users (this would potentially be very wasteful of resources). However, to give users the impression of being recognised as returning visitors, web servers may ask that the web browser keeps some data stored on behalf of the server. When the browser opens a page from that same server, the data is passed along, and the server can act appropriately. Such morsels of data are called cookies.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Swedish cookies
Due to politics, Swedish web sites must inform their visitors if they use cookies and for what purpose. Keep this in mind if you start creating cookie–enabled sites! You should also keep in mind that some people are afraid of cookies and disallow them completely (or erase them as the browser closes). Never rely on cookies for anything, and if you do, state that you are doing so clearly.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Cookie domain scope
Cookies are only accessible from part of the web site. In fact, we limit cookies by domain and by path. A cookie set for the domain “www.asdf.com” will not be accessible on other domains, not even “hello.asdf.com”. A cookie set for “asdf.com”, however, will be accessible to both “www.asdf.com” and “hello.asdf.com”. A cookie cannot be set for some other domain than the current
- ne (we cannot set a cookie for “asdf.com” unless we actually
- wn that domain and the web page setting the cookie is hosted
- n it).
If we omit specifying the domain, the current one is used by default.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Cookie path scope
Assume that we have the following folders on our web server: / /imageGallery/ /imageGallery/vacationPhotos/ /funStuff/ A cookie set for the path “/” can be read from a page residing in any of these folders, whereas a cookie with path “/funStuff/” can only be read by pages in that particular
- folder. Every page that is below the path in the hierarchy can
read a cookie for a “higher” path. If we omit specifying a path, the web page’s own path is the default.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Persistent or session–only
Cookies come in two flavours: persistent or session–only. The difference between the two is that a persistent cookie has an expiration date. Session–only cookies last until the web browser is closed, whereas persistent cookies may (and usually do, unless the user purges them manually) last until their expiration date. To request that a persistent cookie is removed, we can give it an expiration date in the past (say, midnight January 1, 1970).
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Cookie example
In JavaScript, we treat cookies as a very peculiar text string value, accessed via document.cookie. JavaScript performs some “magic” behind the scenes to make document.cookie appear as a string (although it is not). We write to it as if it was a string, and can read from it as well, but we do not get the same string as we put in. See the next slide for an example.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Cookie example
document.cookie = "username=larsson; path=/"; alert(document.cookie); // username=larsson document.cookie = "password=notlikely; path=/"; alert(document.cookie); // username=larsson; password=notlikely document.cookie = "username=hello; path=/"; alert(document.cookie); // username=hello; password=notlikely Note how the username value is replaced, deleting the old one.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Persistent cookies
Persistent cookies are created just like session–only cookies, with the addition of an expiration date, written in the same format as the Date object’s toUTCString() outputs: ...; expires=Mon, Aug 11 2008 14:00:00 GMT;
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Working with cookies
Because all cookies are reported to us as a single string, we have to search inside the string for the information we are looking for. This can be done using the indexOf and substr methods from earlier. Because expiration dates should be in UTC form, it makes good sense for us to use the Date object, rather than creating a correct output string on our own (a good programmer is a lazy programmer. . . at least, up to a point!).
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Working with cookies continued
One final important note: what happens if we wish to store a string containing semi–colons in a cookie? If we are not careful, something like this would be very confusing to the web browser: ...savedStyle=color: red; font-name: sans; path=/... What we should do, simply, is translate such troublesome characters into something “safe” (by replacing the character with a known sequence of safe characters). JavaScript has functions for doing so, called escape and unescape: escape("hello;bye"); // hello%3Bbye unescape("hello%3Bbye") // hello;bye
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Cookie example
The following example shows how to use cookies and provides some easy–to–use functions for handling them (you may use these freely). Also, make sure to look in your Privacy preferences in Firefox, where you can view all cookies and their values. Open example-cookies.xhtml and get to grips with how the code works. Note the use of escape and unescape to make names and values safe with regard to characters such as “;”.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Graceful degradation
Graceful degradation is one of the most important principles in useful web design. The principle is simple: never make the web page depend completely on the presence of support for some technology — it should always be possible to use the web page fully with the simplest of web browsers. If we use semantically correct XHTML and CSS, web browsers that cannot display CSS will get a useful XHTML document
- instead. A user may disable JavaScript due to security
concerns, so we should always strive to make JavaScript
- ptional: if support is present, the site will be more dynamic
but if it is not, the site should still be useful.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Graceful degradation example
Amazon.com provide us with a very nice example of graceful
- degradation. Visit their web page now — once with JavaScript
enabled and once with it disabled. Notice how the menu to the left is different: if JavaScript is enabled, it folds out as the mouse hovers over it, whereas with JavaScript disabled it is expanded the entire time. This is a common example of how things should be handled. You may already imagine what the code must look like and have some idea of how to emulate the effect on your own.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
AJAX introduction
We now turn our attention to AJAX, a popular and trendy technology in modern web design. AJAX is an acronym for Asynchronous JavaScript and XML. Using the DOM manipulation skills that we have covered in previous lectures, AJAX enables us to make dynamic web pages that behave almost like regular desktop applications. A large usability problem with non-AJAX web pages is that data from the user must be submitted and the entire page reloaded (think of a web search). During this reload time, the user is unable to do anything but wait, disrupting the workflow.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
AJAX introduction
AJAX allows us to send and receive data asynchronously (“in the background”). When new data arrives, we can (by using JavaScript) update the page the user is visiting — in effect creating a web page that does not require reloading. Many web pages have incorporated AJAX these days. A popular example of simple AJAX is the smart search box (visit http://sj.se/ for an example of this).
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
AJAX components
The components of AJAX are the following:
- XHTML,
- XHTML DOM manipulation via JavaScript,
- XML, and
- the XMLHttpRequest object.
Since we already know the first two, we devote some time to the latter two.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
XML
Because we have worked with XHTML, we already know XML
- syntax. XML is an acronym for eXtensible Markup Language,
and essentially allows us to create markup languages of our
- wn (that look very similar to XHTML that we already know).
The rules of the languages are expressed in either DTD (Document Type Definition) or in XML Schema. XML Schema is more powerful and the modern choice. If you are interested, the standard for XML Schema can be found here: http://www.w3.org/XML/Schema#dev For instance, we could define a language for CD collections (on next slide).
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
<cdcollection> <cd> <title>Afterglow</title> <artist>Sarah McLachlan</artist> <tracks> <track> <name>Fallen</name> <length unit="seconds">225</length> </track> ... </tracks> </cd> ... </cdcollection>
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
XML continued
As you see, a general XML document looks very familiar to us due to our experience with XHTML. We may also note that, as long as element and attribute names are chosen to be descriptive, XML documents tend to be quite readable by humans. Any kind of data can be expressed in XML. We use this in AJAX-powered web pages: we request that data will be sent to us from a server in some XML format, then use JavaScript methods for parsing the data, and present the result on the web page.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
XML data requests
To request the XML data from the server, we use a special JavaScript object that has been standardised and is called
- XMLHttpRequest. Obtaining a reference to it is simply a
matter of writing the following code: var request = new XMLHttpRequest(); Of course, it was not always as simple as that. If you wish to support older web browsers, particularly Internet Explorer ones, you should use ajaxFunction() found here: http://w3schools.com/ajax/ajax browsers.asp
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Using the XMLHttpRequest object
We cannot cover the XMLHttpRequest object in depth during the lecture, you are encouraged to learn about AJAX on your
- wn using links that will be provided at the end of the lecture.
The XMLHttpRequest object allows us to communicate with a server (send and receive data). It keeps track of the state of the transmission. As soon as the state changes (transmission started, completed, etc), the object will attempt to call a function that we provide it with. The function is responsible for finding out the current state of the transmission and acting accordingly.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Using the XMLHttpRequest object continued
In XMLHttpRequest terms, the state is called the readyState. A reference to the function we write to handle state changes should be fed into the object’s onreadystatechange value. The function is required to accept a number of parameters, because the XMLHttpRequest object depends on it. We set the parameters for the object’s connection to the server with the open() function. It takes a few parameters, the most central of which is the URL we wish to communicate with. To perform the actual communication, we use the send() function, where we may pass along data as well.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Using the XMLHttpRequest object continued
In summary, the basic steps of using XMLHttpRequest are as follows:
- Write a function that handles all readyState changes (will
be called automatically as soon as there is something new to report from the XMLHttpRequest object).
- Create a reference to an XMLHttpRequest object.
- Using the reference, set the onreadystatechange field to
your handler function.
- Initialise the request using the open() function.
- Perform the request using the send() function.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
Handling XML data in JavaScript
The resulting data from our XMLHttpRequest object is XML data, in fact, an XML DOM tree. And we already know how to deal with those! We are given the document node of a DOM tree, and may use all our previous knowledge (adding, removing, and manipulating nodes and attributes) on it. Assuming we called it xmlDoc, we can simply call xmlDoc.getElementById(...) and have it work just as expected.
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary
AJAX further reading
As stated, it is not possible to cover AJAX in any further depth during the lecture. So, you are encouraged to study the specifics on your own: http://www.w3.org/TR/XMLHttpRequest/ http://www.w3schools.com/ajax/ http://javascript.about.com/od/learnajax/ http://sv.wikipedia.org/wiki/AJAX
Advanced JavaScript Lars Larsson Today JavaScript strings JavaScript dates JavaScript timing events JavaScript cookies Graceful degradation AJAX Summary