420 likes | 630 Views
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 ?
E N D
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? • Write a 3D first-person shooter or other game in a Web page? [E.g. paint, trackball, quoridor] • Write Gmail or Google Docs?
Agenda • We'll introduce • JavaScript syntax • jQuery • jQuery UI • Goal: • Familiarity • UI widgets • Light JavaScript/jQuery use to make Web pages interactive
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
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>
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>
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!"); }
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>
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>
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?
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
jQuery • Eases finding things and doing stuff to them! • Highly effective, concise code • Core features: DOM, widgets, events, effects, Ajax • UI plugins
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>
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”); });
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”);
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)
The jQuery Function • $(CSS expression): returns a list of jQuery objects • Selectors: css-like • $(“#navbar”) • $(“ul.navbar li”) • $(“ul.oddevenlist li:even”)
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");
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
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
Manipulation • show(), hide() • slide(), fade() • html(val), text(val) • append(content), prepend(content) [inserting inside] • after(content), before(content) [inserting outside]
How would I… • Example 1 • Example 2 • Example 3 • Menus
jQuery UI • UI Components • Accordion • Autocomplete • Datepicker • Dialog • Menu • Progressbar • Slider • Tabs • Tooltips • UI Interactions • Draggable • Droppable • Resizable • Selectable • Sortable • Themeroller
jQuery Plugins • Repository has thousands of plugins • Areas such as slideshows, media plugins, chat, calendar, WYSIWYG HTML editor, …
jQuery UI Plugins • Farbtastic • lightBox • Star Rating • Tooltip • Tablesorter • Scrollable Table • Drag & drop Tree • Curvy Corners • Heat Colors • DatePicker • ScrollTo • Column Splitter • Pager
Menus • jQuery UI menus • Other menu plugins (find by searching) • superfish • p.sohei.org • Jdsharp.us • 10 best
Ajax in jQuery • Functions • .ajax(): load a page using an HTTP request • .load(): load remote file and insert into DOM • Events: • ajaxComplete(), ajaxError(), ajaxStart(), ajaxSuccess()…
Ajax Examples • Browser-independent ajax queries: $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } });
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?
Make your own Mashup? • How can you use Google Maps or other services on your website? • Find a website that offers an API • Fetch data or resources to make your own page • Data may come back in JSON format • Process it with JavaScript • Add results to your page
JSON • JSON = JavaScript Object Notation • Many services return JSON data
JSON example http://www.hymnary.org/texts?qu=topics:joy http://www.hymnary.org/texts?qu=topics:joy&export=json
Easy way to add photos • How could you add photos from Flickr? • Flickr API?
Flickr Mashup • Flickr offers an API with JSON responses, e.ghttp://api.flickr.com/services/feeds/photos_public.gne?tags=mountain&lang=en-us&format=json&jsoncallback=?
Getting Photos • Fetch the JSON response via AJAX request: • Write a function to add retrieved data to your page
Displaying Photos • Add appropriate HTML to the page • Example