Wa Jquerywebapps PDF

download Wa Jquerywebapps PDF

of 17

Transcript of Wa Jquerywebapps PDF

  • 8/6/2019 Wa Jquerywebapps PDF

    1/17

    Build better web applications with jQuery UI andjQuery plug-ins

    Improving the look and feel of your web pages and applications

    Skill Level: Intermediate

    Christopher Michaelis ([email protected])Developer

    Consultant

    17 May 2011

    Developers who are making the move from desktop applications to web applicationsusing JavaScript and the jQuery library aren't used to thinking about the basic lookand feel of the application because the operating system dealt with that in the past.Discover jQuery UI, a UI toolkit that builds on jQuery, making it easier to produce

    good-looking interfaces. This article also looks at several plug-ins to jQuery thatspeed up web development and help create fluid, intuitive, and flexible interfaces thatlook and feel familiar.

    Introduction

    If you're a traditional desktop application developer making the move to developingweb applications, you probably have no trouble at all picking up HTML and CSS. Butcoming up with a good-looking visual design for your application can be a challenge.

    jQuery UI and various jQuery plug-ins can help a great deal in quickly puttingtogether web applications with minimum time spent on GUI design.

    JavaScript and jQuery

    JavaScript has always been an inherent part of building any web page if you wantthe page to have any degree of dynamic content or interactivity. Without JavaScript,anything you want to do at run time to update your page would require a page

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 1 of 17

    mailto:[email protected]://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/mailto:[email protected]
  • 8/6/2019 Wa Jquerywebapps PDF

    2/17

    refresh, which makes the interface unwieldy. In recent years, the importance ofJavaScript has skyrocketed, as more is done with it and web applications becomemore powerful. JavaScript is even finding a place on the server side throughtechnologies like Node.js, a server-side JavaScript engine. See Resources for linksto more information on Node.js and JavaScript in general, if you want to brush up.

    jQuery is a library primarily used with client-side JavaScript code. It can vastly speedup the time needed to write UI code, providing shortcuts for many day-to-dayactions. It also includes a flexible Ajax library that's useful in creating dynamicinterfaces and is already browser cross-compatible. See Resources for links to moreinformation, including a download link to both development and production copies ofthe library. The production code has been "minified," meaning that all unnecessarywhite space and comments have been removed. The development copy is easier toread if you're exploring the library's internals, which is highly recommended. Beforeusing any third-party library, it pays to inspect it to ensure that you understand andlike both its quality and its functionality.

    jQuery UI

    jQuery UI is a set of UI widgets and CSS styles that come prepackaged toaccomplish common tasks, such as setting up a custom window that prompts a userfor information, through JavaScript and CSS, rather than as an old-style pop-upwindow. When you visit the jQuery UI website (see Resources for a link), you'll seethere is no straight download option. Rather, the site presents a Build customdownload link. Click on this link to assemble your own personalized package inwhich you can clear any components you know you aren't going to use (such as the

    Accordion or Datepicker widgets) to reduce the library size.

    When you download your jQuery UI package, you will notice that there are quite afew files. The development-bundle directory contains demonstrationsanddocumentation, which are useful but not necessary for deployment in production.The files in the css and js directories do need to be deployed to your webapplication, however. The js directory includes both the jQuery and jQuery UIlibraries; the css directory includes the CSS files and all imagery used to producethe widgets and styles.

    Content themes/skins

    The jQuery UI download you assemble from the main page also gives you thechoice of using a particular theme. The jQuery UI page provides a tool to view thevarious themes available right on the site to save time, or you can use the website tobuild your own theme by specifying preferred colors. Doing so basicallyautomatically assembles the necessary CSS settings for you, saving some time. Forexample, Figure 1 shows the Humanity theme (top) compared to the Start theme(bottom). Each theme includes a full set of matching icons.

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 2 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    3/17

    Figure 1. The Humanity theme compared to the Start theme

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 3 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    4/17

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 4 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    5/17

  • 8/6/2019 Wa Jquerywebapps PDF

    6/17

    Figure 2. Comparing a plain alert window to a jQuery UI Dialog widget

    Using the Dialog widget is easiest when you have a separate tag withinyour document holding the content to be displayed. In general, it works well to haveone empty tag that gets reused for dialog boxes. First, set the content, andthen show the dialog box, as Listing 2 shows:

    Listing 2. Displaying a jQuery UI Dialog widget

    in JavaScript code:$('#dialogContent').html('Isn\'t this cooler?

    By setting

    modal to true, you can require the user to dismiss thisbefore interacting

    with more of the page.');

    $('#dialogHolder').dialog({autoOpen: true,title: 'Hello!',modal: true,buttons: {

    "Go Away": function() {$(this).dialog("close");

    }}

    })

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 6 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    7/17

    Interface improvement: Accordions and tabs

    jQuery UI introduces a widget called Accordion, which allows you to have multiplesections of content where, generally, only one section is visible (by default). Clickingon a different section causes the visible section to be hidden with an animation and

    the new section to be shown. One advantage of an accordion is the ability to havevirtually unlimited sections because additional sections are arranged vertically. Thisfunctionality provides a fluid and simple interface.

    Many website visitors will be more familiar with a traditional tab-style layout. Here,the currently selected tab is visible, while other tabs are hidden, effectively limitingthe number of tabs because you're constrained by horizontal width. Figure 3 showsan Accordion widget (top) and a Tab widget (bottom).

    Figure 3. jQuery Accordion and Tab widgets

    Accordions are built using a containing , followed by a sequence of sections.Each section begins with an and an tag, followed by a subcontainer

    that holds your content for each accordion section. Similarly, for the tabcontrols, a containing is used, followed by the definition of the tabsthemselves using a tag. In each , an anchor () is used to tie the tabto the content's . Next, a sequence of elements, with IDs matchingthose defined in the unordered list () defines the actual content. This is easierto see in Listing 3. Once the content has been defined, the accordion or tabfunctionality is initialized by calling .accordion(); or .tab(); on the jQuery

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 7 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    8/17

    selector for the appropriate element.

    Listing 3. Setting up an Accordion widget and a Tab widget

    Next Section

    More content...

  • 8/6/2019 Wa Jquerywebapps PDF

    9/17

    Widget: Datepicker

    A website that has strict requirements of entering a date in a particular format isannoying, particularly if its visitors are from a variety of countries (with their own dateformats). It's also dangerous to leave a free-form input field, which would require

    back-end validation and a means of notifying the visitor if the date entered could notbe parsed. One easy solution is to use a date picker widget, like the one jQuery UIprovides. It has extensive functionality, including the ability to limit date ranges,rename the days on the calendar (for internationalization), and other features. Usingit is simple. Create a standard text input field, such as:

    And then turn it into a calendar using the following code:

    $('#dateDemo').datepicker({ 'maxDate': '+4m'});

    The above code defines a maximum date of four months from the current date (5March 2011, as it happens). The screen shot in Figure 4 reflects this.

    Figure 4. The jQuery UI Datepicker widget

    Building on jQuery animations

    jQuery itself provides the ability to use animate to perform animations thattransition any attribute from one value to another. This functionality is useful whendefining your own animations. But always writing your own animations takes time.

    jQuery UI adds predefined animations, including the stand-alone effects Bounce,Highlight, Pulsate, Shake, Size, and Transfer, and the additional Show and Hideeffects of Blind, Clip, Drop, Explode, Fade, Fold, Puff, Slide, and Scale. These

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 9 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    10/17

    effects are used in the usual jQuery show and hide functions; for example,$('#googleLogo').show('slide', {}, 1000); or$('#googleLogo').hide('explode', {}, 2000);.

    jQuery plug-insDozens of plug-ins have been developed for jQuery by third parties. These plug-insare generally independent of jQuery UI and do not require it, although they dorequire jQuery itself. Let's take a look at some of the particularly useful plug-ins.

    Simple Tree

    Ever since Microsoft Windows Explorer first made its appearance, tree-basedmenus have been popular. They are an easy way to navigate a complex set ofresources, such as documentation. The jQuery Simple Tree plug-in makes it easy toimplement tree menus, with any JavaScript action taken on click. If desired, theplug-in also makes it possible to drag and drop tree items, reorganizing them, alsowith a function fired on drop. (See Resources for a download link; all the requiredcomponents are also available in the sample code in the Download section.) Figure5 shows the Simple Tree plug-in in use.

    Figure 5. The Simple Tree jQuery plug-in

    The tree content is defined with a single outer element, which has an IDidentifying the tree and CSS settings styling it. Inside this, a root item is defined withan element. Inside this element, another element is placed, with treeitems inside this (each one in its own element). Listing 4 illustrates this layout.When complete, the simpleTree function is called to activate tree functionality.

    Listing 4. Setting up a tree menu with Simple Tree

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 10 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    11/17

    Here are some items.

    TopBranch

    Sub itemsare in

    another

    level.

    likethis!

    Another

    BranchLast Branch

    in JavaScript code:$(document).ready(function() {

    $('#treeDemo').simpleTree({autoclose: true,afterClick: function(node) {

    alert($('span:first',node).parent().attr('id') + " wasclicked.");

    },animate: true,drag: false});

    });

    Uploadify

    The Uploadify jQuery plug-in allows you to upload files to your site without having todo a POST operation to a new page and shows a progress indicator as files arebeing uploaded. The upload itself is handled with an Adobe Flash component.The tool allows a great deal of customization, including specifying what fileextensions are allowed, size limits, and whether multiple files can be selected atonce. When each file is finished uploading, the onComplete function is called; theonAllComplete function is called when all files are finished. The default uploadhandler that comes with Uploadify responds by echoing back the name of theuploaded file, but this upload handler can easily be customized to fit your needs (for

    example, posting a file into a forum or taking some other action). Listing 5 showshow to set up a file upload with Uploadify.

    Listing 5. Converting a standard file input to an Uploadify uploader

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 11 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    12/17

    Upload a file to test:

    in JavaScript code:$(document).ready(function() {

    $('#uploadifyDemo').uploadify({'auto': true,'folder': 'tmp','cancelImg': 'uploadify/cancel.png','script': 'uploadify/uploadify.php','uploader': 'uploadify/uploadify.swf',onComplete: function(evt, id, file, resp, data) {

    alert('The file "' + file['name'] + '" with size "'

    + file['size'] +'" was uploaded. (It will be deleted in a fewminutes

    automatically.)' + "\n\nThe upload scriptreturned: " + resp);

    }});

    });

    It's good practice to make sure that your upload directory is either inaccessible to thepublic or well-protected. Failure to do so can allow attackers to upload their owncode and execute it on your server. In this example, files are written to tmp/ in thearticle example directory, so you simply forbid all visitors from accessing tmp/ withan .htaccess rule. It's also important to ensure that the user your web server isrunning as (for example, www-data or apache) has write permission to the uploaddirectory.

    Simpletip

    Any application, whether on a desktop or web-based, needs to be self-documentingfor users to find it truly easy to use. Tooltips are one quick way to do this. Afterdecades of tooltip use, most people are instinctively trained to let their mouse dwellover an item on screen if they are unsure pf what it is, waiting for some pop-up help.The Simpletip plug-in makes this easy to do. With Simpletip, you can create basictooltips or use additional options to control placement. Effects for displaying and

    hiding the tooltips are supported, including custom animations as defined by aJavaScript function. Content for the tooltip can come from hard-coded text or fromany other page content, such as a hidden element, using$('#elementId').html(). You could also programmatically fetch content usingAjax or get it from another source in the document, using something like$('#simpleTip3').simpletip({ content: getToolTip()});. Listing 6illustrates a few different styles of tooltip appearing on words in a sentence.

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 12 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    13/17

    Listing 6. Setting up a tooltips with Simpletip

    SimpleTip lets you add simple

    tooltips,including more advanced

    tooltips or eventooltips with effects

    with a minimum of fuss.

    Fancy content can be defined in a separate

    div.

    in JavaScript code:$(document).ready(function() {

    $('#simpleTip1').simpletip({content: 'A basic tooltip.',fixed: false

    });

    $('#simpleTip2').simpletip({content: $('#simpleTip2Content').html(),fixed: true,position: ['100', '0']

    });

    $('#simpleTip3').simpletip({content: 'Some content to animate',hideEffect: 'slide',showEffect: 'custom',showCustom: function() {

    $(this).css({display: 'block',fontSize: '0.3em',color: '#0000ff',backgroundColor: '#ffffff'

    });$(this).animate({

    color: '#ff0000',fontSize: '1em'

    }, 400);}

    });});

    Conclusion

    Using the tools described in this article allows you to quickly create the visualcomponents of your web application, leaving you free to focus on actual functionality

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 13 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    14/17

    in your site. You still need to think carefully about natural page flow and the usabilityof each page you write in an application, and jQuery UI and these plug-ins do notnegate the need for careful page design. However, they do speed up developmentand make implementation easier. See the Download section for a complete webpage that includes all the discussed sample code. You are welcome to use this as a

    starting point for your own projects.

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 14 of 17

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/6/2019 Wa Jquerywebapps PDF

    15/17

    Downloads

    Description Name Size Downloadmethod

    Source code for examples jQueryUIPluginsExamples.zip 234KB HTTP

    Information about download methods

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 15 of 17

    http://public.dhe.ibm.com/software/dw/web/wa-jquerywebapps/jQueryUIPluginsExamples.ziphttp://www.ibm.com/developerworks/library/whichmethod.htmlhttp://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/developerworks/library/whichmethod.htmlhttp://public.dhe.ibm.com/software/dw/web/wa-jquerywebapps/jQueryUIPluginsExamples.zip
  • 8/6/2019 Wa Jquerywebapps PDF

    16/17

    Resources

    Learn

    JavaScript tutorial (w3schools): Start here if you're new to JavaScript.

    jQuery website: Find downloads and documentation for the jQuery libraryrequired by jQuery UI.

    jQuery UI website: Build your custom download, including only the tools youneed. The site also has great documentation and examples.

    jQuery UI ThemeRoller: Build your own themes, and preview predefinedthemes. The site also makes a handy reference for a quick example of commoncomponents.

    developerWorks Web development zone: Find articles covering variousWeb-based solutions.

    Stay current with developerWorks' technical events and webcasts.

    developerWorks on-demand demos: Watch demos ranging from productinstallation and setup for beginners to advanced functionality for experienceddevelopers.

    Follow developerWorks on Twitter.

    Get products and technologies

    Node.js: Download this fascinating server-side JavaScript engine.

    Simple Tree: Download this jQuery plug-in, which makes it less trivial to buildtree-structure menus, optionally with drag-and-drop support.

    Simpletip: Download this jQuery plug-in that simplifies adding tooltip-stylepop-up windows to any element on your web page.

    Uploadify: Handle file uploads in a clean manner, including progress display,removing the need for a POST and page reload.

    Discuss

    Create your developerWorks profile today and setup a watchlist on jQuery. Getconnected and stay connected with the developerWorks community.

    Find other developerWorks members interested in web development.

    Join one of our developerWorks groups focused on web topics: Share what youknow.

    Roland Barcia talks about Web 2.0 and middleware in his blog.

    Follow developerWorks' members' shared bookmarks on web topics.

    developerWorks ibm.com/developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 16 of 17

    http://www.w3schools.com/js/default.asphttp://jquery.com/http://jqueryui.com/http://jqueryui.com/themeroller/http://www.ibm.com/developerworks/web/http://www.ibm.com/developerworks/offers/techbriefings/http://www.ibm.com/developerworks/offers/lp/demos/http://www.twitter.com/developerworks/http://nodejs.org/http://plugins.jquery.com/project/SimpleTreehttp://craigsworks.com/projects/simpletip/http://www.uploadify.com/https://www.ibm.com/developerworks/mydeveloperworks/profiles/home.do?lang=enhttps://www.ibm.com/developerworks/mydeveloperworks/homepage/help/doc/en/homepage_watchlistuse.htmlhttp://www.ibm.com/developerworks/mydeveloperworks/#communityhttps://www.ibm.com/developerworks/mydeveloperworks/profiles/html/keywordSearch.do?keyword=web&lang=enhttps://www.ibm.com/developerworks/mydeveloperworks/search/web/searchhttps://www.ibm.com/developerworks/mydeveloperworks/blogs/barcia/?lang=enhttps://www.ibm.com/developerworks/mydeveloperworks/bookmarks/html?ps=50&search=web&searchType=mode&sortOrder=desc&lang=enhttp://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/https://www.ibm.com/developerworks/mydeveloperworks/bookmarks/html?ps=50&search=web&searchType=mode&sortOrder=desc&lang=enhttps://www.ibm.com/developerworks/mydeveloperworks/blogs/barcia/?lang=enhttps://www.ibm.com/developerworks/mydeveloperworks/search/web/searchhttps://www.ibm.com/developerworks/mydeveloperworks/profiles/html/keywordSearch.do?keyword=web&lang=enhttp://www.ibm.com/developerworks/mydeveloperworks/#communityhttps://www.ibm.com/developerworks/mydeveloperworks/homepage/help/doc/en/homepage_watchlistuse.htmlhttps://www.ibm.com/developerworks/mydeveloperworks/profiles/home.do?lang=enhttp://www.uploadify.com/http://craigsworks.com/projects/simpletip/http://plugins.jquery.com/project/SimpleTreehttp://nodejs.org/http://www.twitter.com/developerworks/http://www.ibm.com/developerworks/offers/lp/demos/http://www.ibm.com/developerworks/offers/techbriefings/http://www.ibm.com/developerworks/web/http://jqueryui.com/themeroller/http://jqueryui.com/http://jquery.com/http://www.w3schools.com/js/default.asp
  • 8/6/2019 Wa Jquerywebapps PDF

    17/17

    Web 2.0 Apps forum: Get answers quickly.

    Ajax forum: Get answers quickly.

    About the authorChristopher Michaelis

    Christopher Michaelis is a developer specializing in web hosting, webapplications, and GIS programming. He received his education at UtahState University and Idaho State University, studying computer scienceand geographic information science. His experience covers a widerange of development, including applications for environmentalmodeling, education, diabetes data analysis, systems administrationtools, web hosting, platform integration, and location-based services.

    ibm.com/developerWorks developerWorks

    Build better web applications with jQuery UI and jQuery plug-ins Trademarks Copyright IBM Corporation 2011 Page 17 of 17

    http://www.ibm.com/developerworks/forums/forum.jspa?forumID=1182http://www.ibm.com/developerworks/forums/forum.jspa?forumID=965http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/developerworks/forums/forum.jspa?forumID=965http://www.ibm.com/developerworks/forums/forum.jspa?forumID=1182