Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning JavaScript With DOM Scripting And Ajax - From Novice To Professional (2006)

.pdf
Скачиваний:
81
Добавлен:
17.08.2013
Размер:
17.27 Mб
Скачать

416

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

different), and you attract a lot of talent that you may want to hire at a later stage. With a developer network, you see immediately what a person can do instead of having to rely on his CV.

As a developer, this means that if you take a look around the Web, you find an amazing amount of content and technology to play with for free. A good proof of concept is the web site Don’t Meet Your Heroes (http://www.dontmeetyourheroes.com), which is full of web design and web development content that is always up to date due to being syndicated from various RSS feeds from different blogs and magazines. The site therefore offers a lot to the reader, and the maintainers don’t need to spend time writing or researching the content. If the maintainers stumble upon a nice piece of content, it is simple to add, and they also offer a facility for visitors to recommend a resource. The maintainers don’t have much to do, the owners of the listed resource pages get more readers, and the visitors of the site find up-to-date content already collated for them in one spot. Everybody wins.

The Web is also littered with countless third-party JavaScript libraries, which can be downloaded and plugged into your applications, allowing you access to a lot of powerful functionality with very little effort. We’ll look at some examples of these later on in the chapter by looking at jQuery and the Yahoo User Interface Library.

Code Snippets, RSS Feeds, APIs, and Libraries

Probably the oldest type of third-party JavaScript available on the Web are scripts you simply embed into a web site. These could be

Counters recording how many people visit your site, like StatCounter (http:// www.statscounter.com/)

Advertising programs like Google AdSense (https://www.google.com/adsense/)

Previews of your own content added to a product like the Flickr or Yahoo Answers badge

Search tools like TheFreeDictionary’s double-click script (double-click any word in your web site to search for it in TheFreeDictionary—http://www.thefreedictionary.com/ lookup.htm#script)

Another example is script generators that create JavaScripts for you depending on parameters you define. Google AdSense has this feature, and there are dozens of free script generators out on the Web (some are listed at http://www.scriptsearch.com/JavaScript/ Scripts/Generators/). You’d want to handle these script generators especially with care, as a lot of them are outdated and create obtrusive code.

This is a general issue with premade third-party JavaScript. Most such scripts need to be embedded in the body of the document rather than the head and are optimized for performance rather than valid syntax or unobtrusiveness. Many counter scripts also use browser sniffing to determine the user agent (reading out the navigator data instead of using object detection) and are therefore rather inaccurate.

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

417

RSS Feeds and REST APIs

I’ve covered RSS feeds in Chapter 8 already, but it is worth mentioning them again here, as it is amazing what kind of information you can find on the Web for you to use:

There are hardly any news agencies that don’t offer RSS feeds of the latest happenings. Prominent examples of those that do are CNN (http://www.cnn.com/services/rss), Reuters (http://today.reuters.com/rss/newsrss.aspx), and the very geeky The Register (http://www.theregister.co.uk/odds/about/feeds/).

You can get image feeds from Flickr, for example, pictures of San Francisco (http:// flickr.com/photos/tags/sanfrancisco/) and from blogs that deal mainly with images like Cute Overload (http://mfrost.typepad.com/cute_overload/rss.xml).

You can get Podcast information at Podcast Networks (http://www.podcast.net/) and Odeo (http://odeo.com/) in case you want to offer something for those who like to listen rather than read.

The really great service several web sites offer is REST APIs, which allow you to get exactly the information you need.

Note An API (http://www.webopedia.com/TERM/A/API.html) is an application program interface, which is a set of routines and tools to build software applications. Basically, you have a set of methods, objects, and properties to use that allow you to piggyback on the functionality of another program or even operating system. In a sense, you’ve used an API in this book a lot—the browser API that allows you to access the window object with all its methods and the DOM, which allows you to alter and read the document. We’ll get to an API example later on in this chapter when we talk about Google Maps.

I could fill an entire book by going into detail about REST, so a detailed discussion is out of scope here. If you are interested, you can read up on it at Wikipedia (http://en.wikipedia.org/ wiki/Representational_State_Transfer). What REST APIs do is allow you to define in the URL whatever kind of information you want. This could be as simple as adding different data to the URL, for example, to reach different entries of Wikipedia:

http://en.wikipedia.org/wiki/Javascript

http://en.wikipedia.org/wiki/DOM_scripting

Or it can become rather sophisticated, where the API allows you to define the output format of the data and other parameters, for example in Yahoo Search: http://api.search.yahoo.com/ WebSearchService/V1/webSearch?appid=YahooDemo&query=webstandards. This searches for the term “webstandards” in the Yahoo Database and returns an XML string of results. By default, it returns ten results; however, you can limit it to two by adding a parameter: http://api.search.yahoo.com/ WebSearchService/V1/webSearch?appid=YahooDemo&query=webstandards&results=2.

418

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

The API also allows for other parameters like the start of the search result section you want to see or the output format. For example, if you want the results 10 to 15 for the search term “webstandards” in JSON format, you can have that: http://api.search.yahoo.com/WebSearchService/ V1/webSearch?appid=YahooDemo&query=webstandards&results=5&start=10&output=json.

You can use this information directly in JavaScript by sending a callback function name as a parameter to the API:

<script type="text/javascript"> function results(d) {

for(i in d.ResultSet.Result) {

alert( d.ResultSet.Result[i].Title );

}

}</script>

<script type="text/javascript" src="http://api.search.yahoo.com/ WebSearchService/V1/webSearch?appid=YahooDemo &query=webstandards&results=5&start=10& output=json&callback=results"></script>

In short, a REST API allows you to retrieve information from a system in the easiest form, by assembling a static URL, and in the most complex form, to send parameters to customize the output format of that data and call different methods to retrieve different kind of data.

Examples of REST APIs

One example of a REST API is Yahoo’s HotJobs, which allows you to put together a URL to retrieve job offers tailored to your location in the following format: http://hotjobs.yahoo.com/rss/ version/country/state/city/category/keywords.

For example:

This URL searches for JavaScript jobs all across the US and returns an RSS feed: http://hotjobs.yahoo.com/rss/0/USA/-/-/-/javascript.

This URL returns any jobs in Los Angeles, CA: http://hotjobs.yahoo.com/rss/0/USA/ CA/Los+Angeles/-/-.

And this example returns new media and Internet jobs in San Jose: http:// hotjobs.yahoo.com/rss/0/USA/CA/San+Jose/NEW/-.

Another example is Upcoming.org, which is a shared event calendar that lists gigs, exhibitions, and other social events and offers a REST API. For example, you could find all the upcoming events in the following places:

London, England: http://upcoming.org/metro/uk/london/london/

New York City: http://upcoming.org/metro/us/ny/nyc/

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

419

The BBC currently offers a prototype of a REST API at http://www0.rdthdo.bbc.co.uk/ services/api/ that will be part of their other developer offers at http://backstage.bbc.co.uk/ once it has matured enough. This API allows you to browse the BBC program schedule in RSS format. BBC has an Ajax example application available at http://www0.rdthdo.bbc.co.uk/ services/api/examples/ajax/doc.html.

Note You can find more information about REST (Ajax related) in a couple of Christian Gross’s books—

Ajax Patterns and Best Practices (Apress, 2006) and Ajax and REST Recipes (Apress, to be published late 2006).

Using a Library: Short, Shorter, jQuery

One of the main reasons for code libraries is that developers want to make it easier for other developers to achieve day-to-day coding tasks. You’ve done that in this book with the DOMhelp library by creating utility methods to work around browser inconsistencies and solve reoccurring tasks. What you haven’t done is provide your own coding syntax or any other means of reaching elements in the page than the DOM. If you had done that, you could have come up with much shorter code, but also sacrificed the recognition effect of “normal” JavaScript syntax and made development dependent on the knowledge of the library.

There is a trend, however, in JavaScript development to go that route, and many of the large libraries like Rico (http://openrico.org/) and prototype (http://prototype.conio.net/) become more and more daunting in terms of learning the library-specific code syntax and rules in order to achieve a task. Probably the most daring approach in this direction is jQuery (http://jquery.com/), which comprises a single JavaScript file weighing in at only 16K that you add to the head of your documents. It provides you with an amazing amount of utility methods to achieve web-specific tasks. The code you have to write to work with jQuery is very confusing to JavaScript beginners or developers who haven’t dabbled in languages like Ruby, Python, or Java yet. However, it is very powerful all the same once you get your head around it.

The concept of jQuery is to offer quick access to any element of the document, and to get this access you have a utility method called $ (of all things) that takes either

A DOM construct, for example, $( document.body )

A CSS selector, for example, $( 'p a' ), which is every link inside a paragraph in the document

An XPath expression, for example, $(" //a[@rel='nofollow'] "), which matches every link in the document with an attribute called rel that has the value of nofollow

420

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

Note XPath is a W3C standard language to reach parts of an XML document, normally used in connection with XSLT or XPOINTER (http://www.w3.org/TR/xpath). As modern HTML should conform to XML syntax rules (all tags closed, all elements lowercase, attribute values in quotation marks, and single attributes defined as name/value pairs), you can use XPath to find parts of the HTML document, too. Together with XSLT, it is a very powerful tool to convert one XML format to another.

The other trick jQuery has up its sleeve to achieve very short code is a concept called chainable methods, which you already know from the DOM. You can add each method to the last one by concatenating them with a full stop. Instead of

$p = $( 'p' ); $p.addClass( 'test' ); $p.show(); $p.html('example' );

You can use

$( 'p' ).addClass( 'test' ).show().html( 'example' );

Both of these examples do the same: take every paragraph of the document, add a CSS class called test, show the paragraph (in case it was hidden), and change the HTML content of the paragraph to “example”. What jQuery provides you with is an amazing number of these very short-named methods that are tailored to fulfill day-to-day web application development tasks. There is good documentation and examples available on the jQuery site (http:// jquery.com/docs/) and on Mark Constable’s site (http://markc.renta.net/jquery/).

Let’s take a look at an example. If you are a developer and you write tutorials, you often have to show code examples in HTML pages. You wrap them in PRE and CODE elements to make whitespace in the code appear in the right format, like this:

exampleJQuery.html (excerpt)

<h1>Showing and hiding a code example with jQuery</h1> <p>The code</p>

<pre><code>

[... code example ...] </code></pre>

<p>The CSS</p> <pre><code>

[... code example ...] </code></pre>

Let’s now write a script in jQuery that will generate links preceding the code examples that allow for expanding and collapsing the examples instead of simply showing them, as demonstrated in Figure 11-1.

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

421

Figure 11-1. Showing and hiding code examples with jQuery

jqueryTest.js

$( document ) . ready ( function() {

$( 'pre' ).before( '<p><a class="trigger" href="#">Show code</a></p>' );

$( 'pre' ).hide(); $('a.trigger').toggle (

function() { $(this.parentNode.nextSibling).slideDown('slow'); $(this).html( 'Hide Code' );

}, function() {

$(this.parentNode.nextSibling).slideUp('slow'); $(this).html( 'Show Code' );

}

)

}

)

As you can see, the code is amazingly short, but also rather complex in terms of syntax. Let’s go through the example bit by bit so you can understand what is going on:

jqueryTest.js (excerpt)

$( document ) . ready ( function() {

The $(document).ready () method is an event handler that calls the function provided as a parameter (in this case an anonymous function) when the document is ready to be manipulated. This means that everything that follows in this script is executed when the document has loaded—and that means only the document and not all the embedded assets in it like images.

422

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

As you may remember, we talked in Chapter 5 about the ugly effect of the page content showing up before you can hide it. This method works around that problem.

jqueryTest.js (continued)

$( 'pre' ).before( '<p><a class="trigger" href="#">Show code</a></p>' );

$( 'pre' ).hide();

You take every PRE element in the document and use the before() method to add a string of HTML in the DOM tree before this element, in this case, a paragraph with an embedded link with the class trigger. You use the hide() method of jQuery to hide all PRE elements (hide() sets the CSS attribute display to none).

jqueryTest.js (continued)

$('a.trigger').toggle (

You use the CSS selector a.trigger to match all links with the class trigger (which hopefully are only the ones the script added via the before() method) and use the toggle() method. This method alternately executes the two functions provided as parameters when the user clicks the element. The first parameter is an anonymous function that shows the previously hidden code example and changes the link text to “Hide Code” and vice versa.

jqueryTest.js (continued)

function() { $(this.parentNode.nextSibling).slideDown('slow'); $(this).html( 'Hide Code' );

},

You can use several jQuery methods to show and hide elements, the most basic being show() and hide(). A more advanced effect is produced using slideDown() and slideUp(), which show the element in a line-by-line animation. Both of these methods take a parameter that indicates the speed of the animation, which can be slow, normal, or fast. In order to reach the PRE element to show or hide, you need to use the $(this) construct, which returns the event target of toggle(). This means you can use this.parentNode.nextSibling to reach the PRE as the links are nested in a paragraph. You can change the content of the link itself via $(this) and the html() method, which takes a string of HTML as the sole parameter and changes the element’s innerHTML property.

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

423

jqueryTest.js (continued)

function() { $(this.parentNode.nextSibling).slideUp('slow'); $(this).html( 'Show Code' );

}

)

}

)

The other case of toggle() in this example uses slideUp() to slowly hide the code example and changes the text of the link back to “Show Code”.

A really great extension for jQuery (implementations or extensions for jQuery are called plug-ins) is the Ajax plug-in. This plug-in allows for dead-easy Ajax implementations via the load(), $.get(), and $.post() methods as explained at http://jquery.com/docs/ajax/. For example, if you want to create the PRE elements and load the real code examples into them when the user clicks a link, this is pretty easy to do. Check the demo exampleJQueryAjax.html to see the following script in action:

jqueryTestAjax.js

$( document ) . ready ( function() {

$('a.codeExample').each ( function( i ) {

$( this ).after( '<pre class="codeExample"> <code></code></pre>' );

}

)

$( 'pre.codeExample' ).hide(); $('a.codeExample').toggle (

function() {

if( !this.old ){

this.old = $(this).html();

}

$( this ).html('Hide Code'); parseCode( this );

}, function() {

$( this ).html( this.old ); $( this.nextSibling ).hide();

}

424

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

)

function parseCode(o){ if(!o.nextSibling.hascode){

$.get (o.href, function(code){

code=code.replace(/&/mg,'&');

code=code.replace(/</mg,'<');

code=code.replace(/>/mg,'>');

code=code.replace(/\"/mg,'"');

code=code.replace(/\r?\n/g,'<br>');

code=code.replace(/<br><br>/g,'<br>'); code=code.replace(/ /g,' '); o.nextSibling.innerHTML='<code>'+code+'</code>'; o.nextSibling.hascode=true;

}

);

}

$(o.nextSibling).show();

}

}

)

Let’s go through this script step by step:

jqueryTestAjax.js (excerpt)

$( document ) . ready ( function() {

You start once again with the ready() method and an anonymous function (you might as well create a named function and call it via the ready() method).

jqueryTestAjax.js (continued)

$('a.codeExample').each ( function( i ) {

$( this ).after( '<pre class="codeExample"> <code></code></pre>' );

}

)

$( 'pre.codeExample' ).hide();

C H A P T E R 1 1 U S I N G T H I R D - P A R T Y J A V A S C R I P T

425

You use one of jQuery’s iterator methods, each(), to loop through all links that have the CSS class codeExample. You then create PRE elements with the class codeExample and embedded CODE elements after each of these links via the after() method and the $(this) selector before hiding all PRE elements with the codeExample class using jQuery’s hide() method.

jqueryTestAjax.js (continued)

$('a.codeExample').toggle ( function() {

if( !this.old ){

this.old = $(this).html();

}

$( this ).html('Hide Code'); parseCode( this );

}, function() {

$( this ).html( this.old ); $( this.nextSibling ).hide();

}

)

You use toggle() to show and hide the code examples; however, unlike the last script, you store the original text of the link in a property called old when you show the code and replace the link text with “Hide Code”. You then invoke the function parseCode() with the link as a parameter when you show the code. When you hide the code, you restore the original link text by setting the link text back to the value stored in the old parameter before hiding the PRE element with jQuery’s hide() method.

jqueryTestAjax.js (continued)

function parseCode(o){ if(!o.nextSibling.hascode){

$.get (o.href, function(code){

This function tests whether the PRE element following the link (which is its next sibling) has a property called hascode, which you will set once the code has been loaded for the first time. This is necessary to avoid the script loading the code every time the user clicks the link, instead loading it only once. You then use the $.get() method with the link’s href attribute value and an anonymous function as parameters. This will effectively send an XHR request that loads the linked document and invokes the function once the document has been loaded. You send a parameter called code, which will contain the content of the document that was loaded via XHR.