Published on

Mobile applications Development - Lecture 12

jQuery (Zepto)
useful microframeworks

This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).


Published in: Education, Technology, Design
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. jQuery Ivano Malavolta ivano.malavolta@univaq.ithttp://www.di.univaq.it/malavolta
  2. 2. Roadmap• Javascript References• jQuery• Useful Microframeworks
  3. 3. Javascript References• JS Basics – http://www.w3schools.com/js/ You will refine• JS Basics Book your JS knowledge – http://eloquentjavascript.net step-by-step• Object Orientation in JS – http://bit.ly/ILqUXj• Object Orientation in JS (in Italian) Italian) – http://bit.ly/ILr7d1
  4. 4. Roadmap• Javascript References• jQuery• Useful Microframeworks
  5. 5. jQueryA Javascript library for:• manipulating the DOM• adding effects• making Ajax requests
  6. 6. Why jQuery?• Cross-browser compatibility• CSS3 Selectors• Common useful functions – string trimming, AJAX requests, HTML manipulation• Plugins• Unobstrusive Javascript – It easily hooks up to HTML pages• Community – IBM, Google, Microsoft...
  7. 7. jQuery PhilosophyFocus on the interaction between JavaScript and HTML(Almost) every operation boils down to:• Find some stuff• Do something to it
  8. 8. Loading jQueryYou can grab the jQuery library from http://jQuery.comand link to the jQuery script directly<script type="text/javascript” charset="utf-8" src=“.js/lib/jQuery.js" ></script>
  9. 9. jQuery Basics jQuery()This function is the heart of the jQuery libraryYou use this function to fetch elements using CSS selectors and wrap them in jQuery objects so we can manipulate themThere’s a shorter version of the jQuery() function: $() $("h1"); $(".important");
  10. 10. Document Ready$(document).ready(function(){ // Your code here});jQuery has a simple statement that checks the document and waits until its ready to be manipulated
  11. 11. Callback FunctionsA callback is a function that1. is passed as an argument to another function2. is executed after its parent function has completed – when an effect has been completed – when an AJAX call has returned some data$.get(myhtmlpage.html, myCallBack);function myCallBack() { // code}myCallBack is invoked when the $.get is done getting the page
  12. 12. Inline Callback FunctionsA callback function can also be defined in-line$.get(myhtmlpage.html, function() { // code});
  13. 13. Callback Functions with Parameters$.get(myhtmlpage.html, function() { myCallBack(‘Ivano’, ‘Malavolta’);});function myCallBack(name, surname) { // code}
  14. 14. jQuery SelectorsYou can use any CSS2 and CSS3 selectors to fetch elements from the DOM$(‘#nav)$(div#intro h2)$(#nav li.current a)
  15. 15. jQuery Collections$(div.section) returns a jQuery collectionYou can call treat it like an array$(div.section).length = no. of matched elements$(div.section)[0] = the first div DOM element$(div.section)[1]$(div.section)[2]
  16. 16. jQuery CollectionsYou can call methods on jQuery collections$(div.section).size(); // matched elements$(div.section).each(function(i) { console.log("Item " + i + " is ", this);});
  17. 17. HTML elementsYou use the html() method to get and set the inner content of an HTML elementvar text = $(span#msg).html();Some methods return results from the first matched element$(span#msg).text(‘Text to Add);$(div#intro).html(<div>other div</div>);
  18. 18. HTML attributesYou use the attr() method to get and set the attribute of a specific HTML elementvar src = $(a#home).attr(‘href);$(a#home).attr(‘href, ./home.html);$(a#home).attr({ href: ./home.html, id: ‘home});$(a#home).removeAttr(id);
  19. 19. Adding elements to the DOMThe append() method adds a new child element after the existing elementsThere is also prepend()TIP:TIP append as infrequently as possible Every time you append an element to the DOM, the browser needs to recalculate all the positions If you are looping on elements, store them in a var and append only at the end
  20. 20. FormsThe val() method sets and retrieves the value from a form fieldIt works exactly like the html() method
  21. 21. Forms Example<form id="add" > <input type="text" id="task" > <input type="submit" value="Add" ></form>$(function(){ $("#add" ).submit(function(event){ event.preventDefault(); var task = $("#task").val(); });});
  22. 22. CSSYou can use the css() method to define styles on elements$("label" ).css("color" , "#f00" );$("h1" ).css( {"color" : "red" , "text-decoration" : "underline" });
  23. 23. CSSHowever, it’s not a good idea to mix style with scripts. We can use jQuery’s addClass( ) and removeClass( ) methods to add and remove classes when certain events occur$("input" ).focus(function(event){ $(this).addClass("focused" );});$("input" ).blur(function(event){ $(this).removeClass("focused" );});
  24. 24. CSS Examples$(p).css(font-size, 20px);$(p).css({font-size: 20px, color: red});$(#intro).addClass(highlighted);$(#intro).removeClass(highlighted);$(#intro).toggleClass(highlighted);$(p).hasClass(foo);
  25. 25. DOM TraversingjQuery provides enhanced methods for traversing the DOM$(div.intro).parent()$(div.intro).next()$(div.intro).prev()$(div.intro).nextAll(div)$(h1:first).parents()$(li).not(:even).css(background-color, red);
  26. 26. EventsThe .on() method attaches event handlers to the currently selected set of elements in the jQuery object
  27. 27. Event NamesAny event names can be used for the events argument ex. touchstart, touchend, touchmove, blur, focus, submitjQuery will pass through the browsers standard JavaScript event types, calling the handler function when the browser generates eventsThe .trigger() method can be used to manually trigger an event
  28. 28. SelectorWhen a selector is provided, the event handler is referred to as delegatedThe handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector
  29. 29. Selector ExampleDelegated handlers can process events from descendant elements that are added to the document at a later time$("#dataTable tbody tr").on("click", function(event){ alert($(this).text()); });$("#dataTable tbody").on("click", "tr", function(event){ alert($(this).text());});
  30. 30. Event HandlerIt is the function that is called when the event occurs$("button").on(“touchstart", notify);function notify() { console.log(“touched");}event.preventDefault()event.preventDefault() to cancel any default action that the browser may have for this event
  31. 31. Event DataIf a data argument is provided to .on(), it is passed to the handler in the event.data property each time an event is triggeredBest practice is to use an object (map) so that multiple values can be passed as properties
  32. 32. Event Data Example$(“#button1").on(“touchstart", { name: “Ivano" }, greet);$(“#button2").on(“touchstart", { name: “Andrea" }, greet);function greet(event) { alert("Hello “ + event.data.name);}
  33. 33. this VS $(this) VS event$(“div.block”).on(“touchend”, touched);function touched(event) { console.log(this); console.log($(this)); console.log(event);}• this = the DOM element that has been touched• $(this) = the DOM element transformed into a jQuery object $(this) this now you can call jQuery methods on it• event = a jQuery structure containing attributes regarding the (touch) event
  34. 34. .off() and .one().off() to remove events bound with .on().one() one() to attach an event that runs only once and then removes itself
  35. 35. Shorthand methodsThere are shorthand methods for some events that can be used to attach or trigger event handlers.click().blur().focus().scroll().select().submit()...
  36. 36. .on() VS .live() VS .bind()On older guides you may see other functions for managing events like live(), bind(), etc. bind(),on()on() is an attempt to merge most of jQuerys event binding functions into oneIn future versions of jQuery, these methods will be removed and only on() and one() will be left
  37. 37. ChainingMost jQuery methods return another jQuery object, usually one representing the same collectionThis means you can chain methods together:$(div.section).hide().addClass(gone);
  38. 38. Chains EndSome methods return a different collectionYou can call .end() to revert to the previous collection$(#intro).css(color, #cccccc).find(a).addClass(highlighted).end().find(em).css(color, red).end()
  39. 39. AJAXAjax lets us fire requests from the browser to the server without page reload you can update a part of the page while the user continues on workingBasically, you can use AJAX to:• load remote HTML• get JSON data
  40. 40. Load remote HTMLload()grabs an HTML file (even from the server) and insert its contents (everything within the <body> tag) within the current web pageYou can load either static HTML files, or dynamic pages that generate HTML output $(‘#myDiv).load(test.html); $(#myDiv).load(‘test.php div:first);
  41. 41. Cross-site Scripting
  42. 42. Load JSON dataJSON is a lightweight alternative to XML, where data is structured as plain JavaScript objects
  43. 43. Load JSON DataThe URL is a service that returns data in JSON formatIf the feed is in the JSONP format, you’re able to make requests across domains
  44. 44. The Ajax() callAll of jQuery’s Ajax functions are simply wrappers around the $.ajax() method$.ajax({ url: url, This is equivalent to dataType: json, $.getJSON(url, callback); data: data, success: callback, error: callbackError});
  45. 45. A PHP get via Ajax$.ajax({ type: GET, url: getDetails.php, data: { id: 142 }, success: function(data) { // grabbed some data! };});There are more than 20 options for the $.ajax() methodSee http://api.jQuery.com/jQuery.ajax/
  46. 46. EffectsjQuery has built in effects: Differently from CSS3, these are NOT hardware-accelerated $(h1).hide(slow); $(‘div.myBlock).show(); $(h1).slideDown(fast); $(h1).fadeOut(2000);You can chain them: $(h1).fadeOut(1000).slideDown()
  47. 47. Customized Effects$("#block").animate({ width: "+=60px", opacity: 0.4, fontSize: "3em", borderWidth: "10px"}, 1500);Here you can specify the new CSS properties of the element
  48. 48. Roadmap• Javascript References• jQuery• Useful Microframeworks
  49. 49. Useful Microframeworks• Zepto.js• Hammer.js• Underscore.js• Swipe.js
  50. 50. Zepto The only relevant downside of jQuery is about PERFORMANCEHowever,1. It is not very noticeable in current class-A mobile devices2. You can use mobile-suited alternatives to jQuery:
  51. 51. Zepto The goal is to have a ~5-10k modular library that executes fast with a familiar API (jQuery) fast, (jQuery jQuery)It can be seen as amini-jQuerywithout support forolder browsers
  52. 52. Zepto Modules
  53. 53. Zepto UsageSimply replace the reference to jQuery with the one to Zepto
  54. 54. Hammer.jsA javascript library for multi-touch gestures multi-• easy implementation of touch events• lightweight with only 2kb (minified and gzip)• focused library, only for multi-touch gestures• completely standalone
  55. 55. Using Hammer.jsYou can use Hammer by creating:• an Hammer instance for a specific element of the DOM• a callback function for supporting the gesture var hammer = new Hammer(document.getElementById(".block")); hammer.ondragstart = function(event) {...}; hammer.ondrag = function(event) {...}; hammer.ondragend = function(event) {...};
  56. 56. Hammer EventsEvery event returns:• originalEvent the original event of the DOM originalEvent:• position position of the object triggering the event position:• touches: array of touches, it contains an object with touches (x, y) for each finger on the screen
  57. 57. Hammer EventsA Transform gesture event returns:• scale the distance between two fingers since the start scale: of the event. The initial value is 1.0. If less than 1.0 the gesture is pinch close to zoom out. If greater than 1.0 the gesture is pinch open to zoom in.• rotation a delta rotation since the start of an event in rotation: degrees where clockwise is positive and counter- clockwise is negative. The initial value is 0.0.
  58. 58. Hammer EventsA Drag gesture event returns:• angle The angle of the drag movement, where right is 0 angle: degrees, left is -180 degrees, up is -90 degrees and down is 90 degrees• direction Based on the angle, we return a simplified direction: direction, which can be either up, right, down or left• distance The distance of the drag in pixels distance:• distanceX The distance on the X axis of the drag in pixels distanceX:• distanceY The distance on the Y axis of the drag in pixels distanceY:
  59. 59. Underscore.jsA utility library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...)It provides low-level utilities in the following categories:• Collections• Arrays• Objects http://documentcloud.github.com• Functions /underscore/• Utilities
  60. 60. SwipeSwipe is a lightweight mobile slider
  61. 61. Swipe Features1:1 touch movement It tracks the position of the touch and moves the content exactly how the touch interact native feelingResistant bounds When Swipe is at the left-most position, sliding any more left will increase the resistance to slide, making it obvious that you have reached the end
  62. 62. Swipe FeaturesRotation/resize adjustment When a user rotates the device, the slider resets to make sure the sliding elements are the right sizeVariable width containers Swipe allows you to set a width to the containerScroll prevention Swipe detects if you’re trying to scroll down the page or slide content left to rightLibrary agnostic Swipe is totally library independent (even from jQuery)
  63. 63. Swipe UsageThe initial required structure is<div id=sliderId‘> <div> <div>First element</div> <div>Second element </div> <div>Third element </div> </div></div> a series of elements wrapped in two containers
  64. 64. Swipe UsageThen you can attach a Swipe object to a DOM elementwindow.mySwipe = new Swipe( document.getElementById(sliderId));
  65. 65. Swipe UsageOptionally, Swipe() can take a key/value second parameter:• startSlide – index position Swipe should start at• speed – speed of prev and next transitions in milliseconds• callback – a function that runs at the end of any slide change• auto – begin with auto slideshow
  66. 66. Swipe APIFunctions for controlling the Swipe object:• prev() prev() – slide to prev• next() next() – slide to next• getPos() getPos() – returns current slide index position• slide(index, duration) slide(index, – slide to set index position (duration: speed of transition in ms)
  67. 67. Referenceshttp://www.microjs.comhttp://jQuery.comhttp://slidesha.re/IP5MJ5
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.