1 / 46

JavaScript and jQuery

JavaScript and jQuery. Information Systems 337 Prof. Harry Plantinga. How would you…. Make footnotes appear and disappear? Make scripture pop-ups? Show commentary on a verse when it is clicked? Make UI widgets like menus or accordions ?

nat
Download Presentation

JavaScript and jQuery

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript and jQuery Information Systems 337 Prof. Harry Plantinga

  2. How would you… • Make footnotes appear and disappear? • Make scripture pop-ups? • Show commentary on a verse when it is clicked? • Make UI widgets like menus or accordions? • Write a 3D first-person shooter or other game in a Web page? [E.g. paint, trackball, quoridor] • Write Gmail or Google Docs?

  3. Agenda • We'll introduce • JavaScript syntax • jQuery • jQuery UI • Goal: • Familiarity • UI widgets • Light JavaScript/jQuery use to make Web pages interactive

  4. JavaScript • What is JavaScript? • Cross-platform, lightweight, object-oriented scripting language for the Web • Java-like syntax (but not Java) • Limited class library • No disk writing • With HTML5: 2D and 3D graphics, database, multi-threading, . . . . suitable for Web apps

  5. Example <html> <head> <script type="text/javascript"> function message() { var x="This is a string!"; x=1; alert("Hello World!"); for (i=0; i<=64; i++) { document.getElementById("p1").innerHTML += " " + x; x *= 2; } } </script> </head> <body> <input type="button" value="Click me!" onclick="message()" /> <p id="p1">This is a paragraph.<br></p> </body> </html>

  6. Example <html> <head> <script type="text/javascript"> function message() { var x="This is a string!"; x=1; alert("Hello World!"); for (i=0; i<=64; i++) { document.getElementById("p1").innerHTML += " " + x; x *= 2; } } </script> </head> <body> <input type="button" value="Click me!" onclick="message()" /> <p id="p1">This is a paragraph.<br></p> </body> </html>

  7. JavaScript Overview • Java-like syntax • if…else, for, while, try…catch, throw • comments: //, /* */ • variables: var x=5, date=“December 25”, name; • functions: function MyFunc(var1, var2) {…} • arrays: beans = ["Java", "Coffee", "Pinto"]; • objects: var house; house.color = blue; house.warn = function() { alert("Warning, Will Robinson!"); }

  8. Where to Put It • <head>: scripts executed when they are called or when an event triggers <html> <head> <script type="text/javascript”> function message() {alert("This alert box was called with the onload event"); } </script> </head> <body onload="message()”> </body> </html>

  9. Where to Put It • <body>: scripts to be executed when they are loaded <body> <script type="text/javascript”> document.write(“This message is from JavaScript”); </script> </body>

  10. JavaScript Drawbacks • Incompatibility from browser to browser • Difficulty of accessing objects on the web page, modifying them • Sparse class library means you have to roll your own widgets too often (no menus, sliders, color pickers, widgets, etc) • All of your code is visible to the world Why not write a cross-platform library of useful functions?

  11. JavaScript Libraries • General purpose, open source (Stats 2011) • Prototype (23%) • Yahoo UI (11%) • MooTools (13%) • jQuery (38%, growing fastest) • jQuery UI (16%) • Today • jQuery is used almost everywhere, including Drupal

  12. jQuery • Eases finding things and doing stuff to them! • Highly effective, concise code • Core features: DOM, widgets, events, effects, Ajax • UI plugins

  13. jQuery Example <head> ... <script type="text/javascript"> $(document).ready(function() { $("#greenbox").click(function() { $("#greenbox").hide(); $("#redbox").show(); }); $("#redbox").click(function() { $("#redbox").hide(); $("#greenbox").show(); }); }); </script> </head>

  14. jQuery Overview • UI Interactions (e.g. draggable, droppable, sortable) • UI Components (e.g. tree, grid, tabbed pane, toolbar, datepicker) • Consistent look-and-feel for widgets • Elegant transitions • $(“#menu”).slideDown(“slow”); • Events • $(“div”).click(function() { alert(“div clicked”); });

  15. jQuery Overview 2 • Custom events • $(“#list”).bind(“drag”,function(){ $(this).addClass(“dragged”); }); • Finding things in adocument: • $(“div > p:nth-child(odd)”) • Modifying a document: • $(“#li”).append(“<li>An item</li>”); • Ajax • $(“#results”).load(“test.html”);

  16. jQuery Tidbits • More tidbits • Supports IE 6+, Firefox 2+, Safari 2+, Opera 9+ • Core file size (compressed and zipped): 15 k bytes • Code in a public SVN repository • Tutorials online • Books: • Learning jQuery(Packt) • jQuery Reference Guide (Packt)

  17. The jQuery Function • $(CSS expression): returns a list of jQuery objects • Selectors: css-like • $(“#navbar”) • $(“ul.navbar li”) • $(“ul.oddevenlist li:even”)

  18. jQuery selectors • Basics: #id, element, .class, * • Hierarchy: parent > child, prev + next, prev ~ sib • Basic filters: :first :last :not(selector) :even :odd :eq(index) :gt(index) :lt(index) :header :animated • Content filters: :contains(text) :empty :has(selector) :parent • Attribute filters: [attribute] [attribute=value] etc. • Child filters: e.g. :nth-child(even), :first-child • Examples $('a[href^="http://"]').attr({ target: "_blank" }); $("ul li:even").addClass("even"); $("ul li:odd").addClass("odd");

  19. jQuery Attributes Things you can retrieve or set for objects: • attr() or attr(key, value) – get or set attribute • removeAttr(name) • hasClass(), addClass(), removeClass(), toggleClass() • html(), html(val) – get or set HTML contents • text() or text(val) – get or set text contents

  20. jQuery Events • Example event functions • ready (fn) // when the DOM is ready to be manipulated • bind(type, data, fn) // bind a handler to an event • toggle(fn, fn2) // toggle between two or more functions on click • trigger(event, data) //trigger an event on each matched element • Event types • blur, change, click, dblclick, error, focus, keyup, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, resize, scroll, select, submit, unload

  21. Manipulation • show(), hide() • slide(), fade() • html(val), text(val) • append(content), prepend(content) [inserting inside] • after(content), before(content) [inserting outside]

  22. How would I… • Example 1 • Example 2 • Example 3 • Menus

  23. jQuery UI • UI Components • Accordion • Autocomplete • Datepicker • Dialog • Menu • Progressbar • Slider • Tabs • Tooltips • UI Interactions • Draggable • Droppable • Resizable • Selectable • Sortable • Themeroller

  24. jQuery Plugins • Repository has thousands of plugins • Areas such as slideshows, media plugins, chat, calendar, WYSIWYG HTML editor, …

  25. jQuery UI Plugins • Farbtastic • lightBox • Star Rating • Tooltip • Tablesorter • Scrollable Table • Drag & drop Tree • Curvy Corners • Heat Colors • DatePicker • ScrollTo • Column Splitter • Pager

  26. Menus • jQuery UI menus • Other menu plugins (find by searching) • Superfish • Jdsharp.us • 10 best

  27. Ajax in jQuery • Functions • .ajax(): load a page asynchronously using an HTTP request • .load(): load remote file and insert into DOM • Events: • ajaxComplete(), ajaxError(), ajaxStart(), ajaxSuccess()…

  28. Ajax Examples • Browser-independent ajax queries: $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } });

  29. Mashups

  30. Mashups

  31. Web Services • What is a Web Service? • According to the W3C, a “Web Service” is: …a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards. http://www.w3.org/DesignIssues/WebServices.html

  32. REST • Representational State Transfer: • Client-server (web-based) • Standard semantics for HTTP requests (GET, PUT, etc) • Resources have URLs • Standard methods and media for data interchange (e.g. png, JSON, xml) • Stateless • Scalable, cached • A predominant Web API mode

  33. Adding Images • Suppose your client wanted to be able to add images to Flickr and have them appear on their website. Can this be done?

  34. Flickr • Flickr offers an API that lets you control your flickr account, upload photos, display photos, create mashups, etc. • API documentation • App Garden

  35. Flickr API • Flickr API can give JSON responses, e.ghttp://api.flickr.com/services/feeds/photos_public.gne?tags=mountain&lang=en-us&format=json&jsoncallback=?

  36. JSON • JSON = JavaScript Object Notation • Many services return JSON data • Use example: [object].postalCode

  37. JSON example http://www.hymnary.org/texts?qu=topics:joy http://www.hymnary.org/texts?qu=topics:joy&export=json

  38. jQuery, AJAX, JSON

  39. jQuery.each()

  40. Getting Photos • Fetch the JSON response via AJAX request: • Write a function to add retrieved data to your page

  41. Displaying Photos • Add appropriate HTML to the page • Example

  42. Make your own Mashup • Say you want to let users enter a location and display pictures, info, and a map. How? • Pictures? • Maps? • Look up Google Maps API • Information? • Look up Freebase API • Steps • Fetch resources vi AJAX • Add returned JSON data to your page with JavaScript

  43. Google Maps • Very powerful API lets you create almost any map-based Web app

  44. Freebase • “A community-curated database of well-known people, places, and things” • Stores facts about entities in RDF format • Search services returns JSON • API documentation • Search for Boston • Facts about Boston(see /common/topic/description)

More Related