Top Banner
jQuery Ivano Malavolta Ivano Malavolta [email protected] http://www.di.univaq.it/malavolta
67

jQuery

May 17, 2015

Download

Education

Mobile applications Development - Lecture 12

Javascript
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).

http://www.di.univaq.it/malavolta
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: jQuery

jQuery

Ivano MalavoltaIvano Malavolta

[email protected]

http://www.di.univaq.it/malavolta

Page 2: jQuery

Roadmap

• Javascript References

• jQuery• jQuery

• Useful Microframeworks

Page 3: jQuery

Javascript References

• JS JS JS JS BasicsBasicsBasicsBasics– http://www.w3schools.com/js/– http://www.w3schools.com/js/

• JS JS JS JS BasicsBasicsBasicsBasics BookBookBookBook– http://eloquentjavascript.net

• Object Orientation in JSObject Orientation in JSObject Orientation in JSObject Orientation in JS

You will refineyour JS knowledgestep-by-step

Object Orientation in JSObject Orientation in JSObject Orientation in JSObject Orientation in JS– http://bit.ly/ILqUXj

• ObjectObjectObjectObject OrientationOrientationOrientationOrientation in JS (in in JS (in in JS (in in JS (in ItalianItalianItalianItalian))))– http://bit.ly/ILr7d1

Page 4: jQuery

Roadmap

• Javascript References

• jQuery• jQuery

• Useful Microframeworks

Page 5: jQuery

jQuery

A Javascript library for:

• manipulating the DOM

• adding effects

• making Ajax requests

Page 6: jQuery

Why jQuery?

• Cross-browser compatibility

• CSS3 Selectors• 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...

Page 7: jQuery

jQuery Philosophy

Focus on the interaction between JavaScript and HTML

(Almost) every operation boils down to:

• Find some stuff

• Do something to it

Page 8: jQuery

Loading jQuery

You can grab the jQuery library from http://jQuery.com

and link to the jQuery script directlyand link to the jQuery script directly

<script type="text/javascript” charset="utf-8"

src=“.js/lib/jQuery.js" >

</script>

Page 9: jQuery

jQuery Basics

jQuery()

This function is the heart of the 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");

Page 10: jQuery

Document Ready

$(document).ready(function(){ $(document).ready(function(){

// Your code here

});

jQuery has a simple statement that checks the document and waits until it's ready to be manipulateddocument and waits until it's ready to be manipulated

Page 11: jQuery

Callback Functions

A callback is a function that 1. is 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

Page 12: jQuery

Inline Callback Functions

A callback function can also be defined in-line

$.get('myhtmlpage.html', function() {

// code

});

Page 13: jQuery

Callback Functions with Parameters

$.get('myhtmlpage.html', function() {

myCallBack(‘Ivano’, ‘Malavolta’);

});

function myCallBack(name, surname) {function myCallBack(name, surname) {

// code

}

Page 14: jQuery

jQuery Selectors

You can use any CSS2 and CSS3 selectors to fetch elements from the DOMelements from the DOM

$(‘#nav')

$('div#intro h2')

$('#nav li.current a')

Page 15: jQuery

jQuery Collections

$('div.section') returns a jQuery collection

You can call 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]

Page 16: jQuery

jQuery Collections

You can call methods on jQuery collections

$('div.section').size(); // matched elements

$('div.section').each(function(i) {

console.log("Item " + i + " is ", this);console.log("Item " + i + " is ", this);

});

Page 17: jQuery

HTML elements

You use the html() method to get and set the inner content of an HTML elementcontent 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>');

Page 18: jQuery

HTML attributes

You use the attr() method to get and set the attribute of a specific HTML elementof 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');

Page 19: jQuery

Adding elements to the DOM

The append() method adds a new child element after the existing elementsafter the existing elements

There is also prepend()

TIPTIPTIPTIP: 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 varand append only at the end

Page 20: jQuery

Forms

The val() method sets and retrieves the value from a form fielda form field

It works exactly like the html() method

Page 21: jQuery

Forms Example

<form id="add" >

<input type="text" id="task" ><input type="text" id="task" >

<input type="submit" value="Add" >

</form>

$(function(){

$("#add" ).submit(function(event){

event.preventDefault();event.preventDefault();

var task = $("#task").val();

});

});

Page 22: jQuery

CSS

You can use the css() method to define styles on elementselements

$("label" ).css("color" , "#f00" );

$("h1" ).css(

{"color" : "red" ,{"color" : "red" ,

"text-decoration" : "underline" }

);

Page 23: jQuery

CSS

However, it’s not a good idea to mix style 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" );

});

Page 24: jQuery

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');

Page 25: jQuery

DOM Traversing

jQuery provides enhanced methods for traversing the DOM

$('div.intro').parent()

$('div.intro').next()

$('div.intro').prev()

$('div.intro').nextAll('div')

$('h1:first').parents()$('h1:first').parents()

$('li').not(':even').css('background-color',

'red');

Page 26: jQuery

Events

The .on() method attaches event handlers to the currently selected set of elements in the jQuerycurrently selected set of elements in the jQueryobject

Page 27: jQuery

Event Names

Any event names can be used for the events argumentex. touchstart, touchend, touchmove, blur, focus, submitex. 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

Page 28: jQuery

Selector

When a selector is provided, the event handler is referred to as delegatedreferred 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 selectorselector

Page 29: jQuery

Selector Example

Delegated handlers can process events from descendant elements 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());

});

Page 30: jQuery

Event Handler

It is the function that is called when the event occurs

$("button").on(“touchstart", notify);

function notify() {

console.log(“touched");

}}

event.preventDefaultevent.preventDefaultevent.preventDefaultevent.preventDefault()()()()to cancel any default action that the browser may have for this event

Page 31: jQuery

Event Data

If a data argument is provided to .on(), 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 propertiesmultiple values can be passed as properties

Page 32: jQuery

Event Data Example

$(“#button1").on(“touchstart",

{ name: “Ivano" }, greet); { name: “Ivano" }, greet);

$(“#button2").on(“touchstart",

{ name: “Andrea" }, greet);

function greet(event) { function greet(event) {

alert("Hello “ + event.data.name);

}

Page 33: jQuery

this VS $(this) VS event

$(“div.block”).on(“touchend”, touched);

function touched(event) {

console.log(this);

console.log($(this));

console.log(event);

}

• thisthisthisthis = the DOM element that has been touched• thisthisthisthis = the DOM element that has been touched

• $($($($(thisthisthisthis) ) ) ) = the DOM element transformed into a jQuery object

now you can call jQuery methods on it

• eventeventeventevent = a jQuery structure containing attributes regardingthe (touch) event

Page 34: jQuery

.off() and .one()

.off().off().off().off().off().off().off().off()

to remove events bound with .on()

....oneoneoneone()()()()....oneoneoneone()()()()

to attach an event that runs only once and then removes itself

Page 35: jQuery

Shorthand methods

There are shorthand methods for some events that can be used to attach or trigger event handlersused to attach or trigger event handlers

.click()

.blur()

.focus()

.scroll()

.select()

.submit()

...

Page 36: jQuery

.on() VS .live() VS .bind()

On older guides you may see other functions forOn older guides you may see other functions formanaging events like live(), live(), live(), live(), bindbindbindbind(), etc.(), etc.(), etc.(), etc.

onononon()()()() 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

Page 37: jQuery

Chaining

Most jQuery methods return another jQuery object, usually one representing the same collectionusually one representing the same collection

This means you can chain methods together:

$('div.section').hide().addClass('gone');

Page 38: jQuery

Chains End

Some methods return a different collection

You can call .end() .end() .end() .end() to revert to the previous collection

$('#intro').css('color', '#cccccc').

find('a').addClass('highlighted').end().

find('em').css('color', 'red').end()find('em').css('color', 'red').end()

Page 39: jQuery

AJAX

Ajax lets us fire requests from the browser to the server without page without page without page without page reloadreloadreloadreloadserver without page without page without page without page reloadreloadreloadreload

� 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

Page 40: jQuery

Load remote HTML

load()

grabs an HTML file (even from 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');

Page 41: jQuery

Cross-site Scripting

Page 42: jQuery

Load JSON dataJSON is a lightweight alternative to XML, where data is structured as plain JavaScript objects

Page 43: jQuery

Load JSON Data

The URL is a service that returns data in JSON formatThe 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

Page 44: jQuery

The Ajax() call

All of jQuery’s Ajax functions are simply wrappers around the $.ajax() methodaround the $.ajax() method

$.ajax({

url: url,

dataType: 'json',

data: data,

This is equivalent to$.getJSON(url, callback);

data: data,

success: callback,

error: callbackError

});

Page 45: jQuery

A PHP get via Ajax

$.ajax({

type: 'GET', type: 'GET',

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/

Page 46: jQuery

Effects

jQuery has built in effects: Differently from CSS3, these are NOT

$('h1').hide('slow');

$(‘div.myBlock).show();

$('h1').slideDown('fast');

$('h1').fadeOut(2000);

these are NOThardware-accelerated

You can chain them:$('h1').fadeOut(1000).slideDown()

Page 47: jQuery

Customized Effects

$("#block").animate({

width: "+=60px",width: "+=60px",

opacity: 0.4,

fontSize: "3em",

borderWidth: "10px"

}, 1500);

Here you can specify the new CSS properties of the element

Page 48: jQuery

Roadmap

• Javascript References

• jQuery• jQuery

• Useful Microframeworks

Page 49: jQuery

Useful Microframeworks

• Zepto.js

• Hammer.js• Hammer.js

• Underscore.js

• Swipe.js

Page 50: jQuery

Zepto

The only relevant downside of jQuery is aboutPERFORMANCEPERFORMANCEPERFORMANCEPERFORMANCEPERFORMANCEPERFORMANCEPERFORMANCEPERFORMANCE

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:

Page 51: jQuery

Zepto

The goal is to have a ~5-10k modular library that executes executes executes executes fastfastfastfast, with a familiar familiar familiar familiar API (API (API (API (jQueryjQueryjQueryjQuery))))executes executes executes executes fastfastfastfast, with a familiar familiar familiar familiar API (API (API (API (jQueryjQueryjQueryjQuery))))

It can be seen as a

mini-jQuery

without support for

older browsers

Page 52: jQuery

Zepto Modules

Page 53: jQuery

Zepto Usage

Simply replace the reference to jQuery with the one toZeptoZepto

Page 54: jQuery

Hammer.js

A javascript library for multimultimultimulti----touch gesturestouch gesturestouch gesturestouch gestures

• easy implementation of touch events

• lightweight with only 2kb (minified and gzip)

• focused library, only for multi-touch gestures

• completely standalone• completely standalone

Page 55: jQuery

Using Hammer.js

You can use Hammer by creating:

• anananan HammerHammerHammerHammer instanceinstanceinstanceinstance for a specific element of the DOM

• a a a a callbackcallbackcallbackcallback functionfunctionfunctionfunction 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) {...};

Page 56: jQuery

Hammer Events

Every event returns:

• originalEventoriginalEventoriginalEventoriginalEvent: the original event of the DOM

• positionpositionpositionposition: position of the object triggering the event

• touchestouchestouchestouches: array of touches, it contains an object with(x, y) for each finger on the screen

Page 57: jQuery

Hammer Events

A Transform gesture event returns:

• scalescalescalescale: 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.

• rotationrotationrotationrotation: a delta rotation since the start of an event in • rotationrotationrotationrotation: 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.

Page 58: jQuery

Hammer Events

A Drag gesture event returns:

• angleangleangleangle: The angle of the drag movement, where right is 0 degrees, left is -180 degrees, up is -90 degrees and down is 90 degrees

• directiondirectiondirectiondirection: Based on the angle, we return a simplified direction, which can be either up, right, down or leftdirection, which can be either up, right, down or left

• distancedistancedistancedistance: The distance of the drag in pixels

• distanceXdistanceXdistanceXdistanceX: The distance on the X axis of the drag in pixels

• distanceYdistanceYdistanceYdistanceY: The distance on the Y axis of the drag in pixels

Page 59: jQuery

Underscore.js

A utility library utility library utility library utility library for JavaScript that provides support for the usual functional suspects (each, map, reduce, the usual functional suspects (each, map, reduce, filter...)

It provides low-level utilities in the following categories:• CollectionsCollectionsCollectionsCollections• ArraysArraysArraysArrays• ObjectsObjectsObjectsObjects http://documentcloud.github.com• ObjectsObjectsObjectsObjects• FunctionsFunctionsFunctionsFunctions• UtilitiesUtilitiesUtilitiesUtilities

http://documentcloud.github.com/underscore/

Page 60: jQuery

Swipe

Swipe is a lightweight mobile slider

Page 61: jQuery

Swipe Features

1:1 touch movement1:1 touch movement1:1 touch movement1:1 touch movement1:1 touch movement1:1 touch movement1:1 touch movement1:1 touch movementIt tracks the position of the touch and moves the content exactly how the touch interact � native feeling

Resistant boundsResistant boundsResistant boundsResistant boundsResistant boundsResistant boundsResistant boundsResistant boundsWhen 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

Page 62: jQuery

Swipe Features

Rotation/resize adjustmentRotation/resize adjustmentRotation/resize adjustmentRotation/resize adjustmentWhen 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 containersVariable width containersVariable width containersVariable width containersSwipe allows you to set a width to the container

Scroll preventionScroll preventionScroll preventionScroll preventionSwipe 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 agnosticLibrary agnosticLibrary agnosticLibrary agnosticSwipe is totally library independent (even from jQuery)

Page 63: jQuery

Swipe Usage

The initial required structure is

<div id='sliderId‘>

<div>

<div>First element</div>

<div>Second element </div>

<div>Third element </div>

</div></div>

</div>

� a series of elements wrapped in two containers

Page 64: jQuery

Swipe Usage

Then you can attach a Swipe object to a DOM element

window.mySwipe = new Swipe(

document.getElementById('sliderId'));

Page 65: jQuery

Swipe Usage

Optionally, Swipe() can take a key/value second parameter:

• startSlidestartSlidestartSlidestartSlide

– index position Swipe should start at

• speedspeedspeedspeed

– speed of prev and next transitions in milliseconds– speed of prev and next transitions in milliseconds

• callbackcallbackcallbackcallback

– a function that runs at the end of any slide change

• autoautoautoauto

– begin with auto slideshow

Page 66: jQuery

Swipe API

Functions for controlling the Swipe object:

• prevprevprevprev() () () () – slide to prev

• nextnextnextnext() () () () – slide to next

• getPosgetPosgetPosgetPos() () () () • getPosgetPosgetPosgetPos() () () () – returns current slide index position

• slide(indexslide(indexslide(indexslide(index, duration) , duration) , duration) , duration) – slide to set index position (duration: speed of transition in ms)

Page 67: jQuery

References

http://www.microjs.com

http://jQuery.com

http://slidesha.re/IP5MJ5