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).
Basics – http://www.w3schools.com/js/ – http://www.w3schools.com/js/ • JS JS JS JS Basics Basics Basics Basics Book Book Book Book – http://eloquentjavascript.net • Object Orientation in JS Object Orientation in JS Object Orientation in JS Object Orientation in JS You will refine your JS knowledge step-by-step Object Orientation in JS Object Orientation in JS Object Orientation in JS Object Orientation in JS – http://bit.ly/ILqUXj • Object Object Object Object Orientation Orientation Orientation Orientation in JS (in in JS (in in JS (in in JS (in Italian Italian Italian Italian) ) ) ) – http://bit.ly/ILr7d1
Selectors • Common useful functions – string trimming, AJAX requests, HTML manipulation • Plugins • Unobstrusive Javascript – It easily hooks up to HTML pages • Community – IBM, Google, Microsoft...
and link to the jQuery script directly and link to the jQuery script directly <script type="text/javascript” charset="utf-8" src=“.js/lib/jQuery.js" > </script>
jQuery library You use this function to fetch elements using CSS selectors and wrap them in jQuery objects so we can manipulate them There’s a shorter version of the jQuery() function: $() $("h1"); $(".important");
passed as an argument to another function 1. is passed as an argument to another function 2. 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() { function myCallBack() { // code } myCallBack is invoked when the '$.get' is done getting the page
treat it like an array $('div.section').length = no. of matched elements $('div.section')[0] = the first div DOM element $('div.section')[0] = the first div DOM element $('div.section')[1] $('div.section')[2]
set the inner content of an HTML element content of an HTML element var 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>');
set the attribute of a specific HTML element of a specific HTML element var src = $('a#home').attr(‘href'); $('a#home').attr(‘href', './home.html'); $('a#home').attr({ $('a#home').attr({ 'href': './home.html', 'id': ‘home' }); $('a#home').removeAttr('id');
new child element after the existing elements after the existing elements There is also prepend() TIP TIP TIP TIP: append as infrequently as possible Every time you append an element to the DOM, the 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
with scripts. We can use jQuery’s addClass( ) and removeClass( ) 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" ); });
events argument ex. touchstart, touchend, touchmove, blur, focus, submit ex. touchstart, touchend, touchmove, blur, focus, submit jQuery will pass through the browser's standard JavaScript event types, calling the handler function when the browser generates events The .trigger() .trigger() .trigger() .trigger() method can be used to manually trigger an event
referred to as delegated referred to as delegated The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector selector
that are added to the document at a later 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()); });
the event occurs $("button").on(“touchstart", notify); function notify() { console.log(“touched"); } } event.preventDefault event.preventDefault event.preventDefault event.preventDefault() () () () to cancel any default action that the browser may have for this event
it is passed to the handler in the event.data passed to the handler in the event.data property each time an event is triggered Best practice is to use an object (map) so that multiple values can be passed as properties multiple values can be passed as properties
console.log(this); console.log($(this)); console.log(event); } • this this this this = the DOM element that has been touched • this this this this = the DOM element that has been touched • $( $( $( $(this this this this) ) ) ) = the DOM element transformed into a jQuery object now you can call jQuery methods on it • event event event event = a jQuery structure containing attributes regarding the (touch) event
.off() to remove events bound with .on() . .. .one one one one() () () () . .. .one one one one() () () () to attach an event that runs only once and then removes itself
see other functions for On older guides you may see other functions for managing events like live(), live(), live(), live(), bind bind bind bind(), etc. (), etc. (), etc. (), etc. on on on on() () () () is an attempt to merge most of jQuery's event binding functions into one In future versions of jQuery, these methods will be removed and only on() and one() will be left
representing the same collection usually one representing the same collection This means you can chain methods together: $('div.section').hide().addClass('gone');
the server without page without page without page without page reload reload reload reload server without page without page without page without page reload reload reload reload you can update a part of the page while the user continues on working Basically, you can use AJAX to: Basically, you can use AJAX to: • load remote HTML • get JSON data
the server) and insert its grabs an HTML file (even from the server) and insert its contents (everything within the <body> tag) within the current web page You can load either static HTML files, or dynamic pages that generate HTML output $(‘#myDiv').load('test.html'); $('#myDiv').load(‘test.php div:first');
data in JSON format The URL is a service that returns data in JSON format If the feed is in the JSONP format, you’re able to make requests across domains
wrappers around the $.ajax() method around the $.ajax() method $.ajax({ url: url, dataType: 'json', data: data, This is equivalent to $.getJSON(url, callback); data: data, success: callback, error: callbackError });
url: 'getDetails.php', data: { id: 142 }, success: function(data) { // grabbed some data! }; }; }); There are more than 20 options for the $.ajax() method See http://api.jQuery.com/jQuery.ajax/
are NOT $('h1').hide('slow'); $(‘div.myBlock).show(); $('h1').slideDown('fast'); $('h1').fadeOut(2000); these are NOT hardware-accelerated You can chain them: $('h1').fadeOut(1000).slideDown()
PERFORMANCE PERFORMANCE PERFORMANCE PERFORMANCE PERFORMANCE PERFORMANCE PERFORMANCE However, 1. It is not very noticeable in current class-A mobile devices 2. You can use mobile-suited alternatives to jQuery: 2. You can use mobile-suited alternatives to jQuery:
that executes executes executes executes fast fast fast fast, with a familiar familiar familiar familiar API ( API ( API ( API (jQuery jQuery jQuery jQuery) ) ) ) executes executes executes executes fast fast fast fast, with a familiar familiar familiar familiar API ( API ( API ( API (jQuery jQuery jQuery jQuery) ) ) ) It can be seen as a mini-jQuery without support for older browsers
an an an Hammer Hammer Hammer Hammer instance instance instance instance for a specific element of the DOM • a a a a callback callback callback callback function function function function for supporting the gesture var hammer = new Hammer(document.getElementById(".block")); var hammer = new Hammer(document.getElementById(".block")); hammer.ondragstart = function(event) {...}; hammer.ondrag = function(event) {...}; hammer.ondragend = function(event) {...};
the original event of the DOM • position position position position: position of the object triggering the event • touches touches touches touches: array of touches, it contains an object with (x, y) for each finger on the screen
scale scale: the distance between two fingers since the start 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 rotation rotation rotation: a delta rotation since the start of an event in • rotation rotation rotation rotation: a delta rotation since the start of an event in degrees where clockwise is positive and counter- clockwise is negative. The initial value is 0.0.
angle angle: The angle of the drag movement, where right is 0 degrees, left is -180 degrees, up is -90 degrees and down is 90 degrees • direction direction direction direction: Based on the angle, we return a simplified direction, which can be either up, right, down or left direction, which can be either up, right, down or left • distance distance distance distance: The distance of the drag in pixels • distanceX distanceX distanceX distanceX: The distance on the X axis of the drag in pixels • distanceY distanceY distanceY distanceY: The distance on the Y axis of the drag in pixels
movement 1:1 touch movement 1:1 touch movement 1:1 touch movement 1:1 touch movement 1:1 touch movement It tracks the position of the touch and moves the content exactly how the touch interact native feeling Resistant bounds Resistant bounds Resistant bounds Resistant bounds Resistant bounds Resistant bounds Resistant bounds Resistant 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
When a user rotates the device, the slider resets to make sure the sliding elements are the right size sure the sliding elements are the right size Variable width containers Variable width containers Variable width containers Variable width containers Swipe allows you to set a width to the container Scroll prevention Scroll prevention Scroll prevention Scroll prevention Swipe detects if you’re trying to scroll down the page or Swipe detects if you’re trying to scroll down the page or slide content left to right Library agnostic Library agnostic Library agnostic Library agnostic Swipe is totally library independent (even from jQuery)
• startSlide startSlide startSlide startSlide – index position Swipe should start at • speed speed speed speed – speed of prev and next transitions in milliseconds – speed of prev and next transitions in milliseconds • callback callback callback callback – a function that runs at the end of any slide change • auto auto auto auto – begin with auto slideshow
prev prev prev() () () () – slide to prev • next next next next() () () () – slide to next • getPos getPos getPos getPos() () () () • getPos getPos getPos getPos() () () () – returns current slide index position • slide(index slide(index slide(index slide(index, duration) , duration) , duration) , duration) – slide to set index position (duration: speed of transition in ms)