SlideShare a Scribd company logo
jQuery
         Ivano Malavolta
    ivano.malavolta@univaq.it
http://www.di.univaq.it/malavolta
Roadmap

• Javascript References
• jQuery
• Useful Microframeworks
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
Roadmap

• Javascript References
• jQuery
• Useful Microframeworks
jQuery

A Javascript library for:

• manipulating the DOM
• adding effects
• making Ajax requests
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...
jQuery Philosophy

Focus on the interaction between JavaScript and HTML

(Almost) every operation boils down to:
• Find some stuff
• Do something to it
Loading jQuery

You can grab the jQuery library from http://jQuery.com
and link to the jQuery script directly


<script type="text/javascript” charset="utf-8"
  src=“.js/lib/jQuery.js" >
</script>
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");
Document Ready

$(document).ready(function(){
  // Your code here
});


jQuery has a simple statement that checks the
  document and waits until it's ready to be manipulated
Callback Functions
A callback is a function that
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() {
   // code
}

myCallBack is invoked when the '$.get' is done getting the page
Inline Callback Functions

A callback function can also be defined in-line



$.get('myhtmlpage.html', function() {
   // code
});
Callback Functions with Parameters



$.get('myhtmlpage.html', function() {
   myCallBack(‘Ivano’, ‘Malavolta’);
});

function myCallBack(name, surname) {
   // code
}
jQuery Selectors

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

$(‘#nav')
$('div#intro h2')
$('#nav li.current a')
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')[1]
$('div.section')[2]
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);
});
HTML elements
You use the html() method to get and set the inner
  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>');
HTML attributes
You use the attr() method to get and set the attribute
  of a specific HTML element

var src = $('a#home').attr(‘href');

$('a#home').attr(‘href', './home.html');

$('a#home').attr({
  'href': './home.html',
  'id': ‘home'
});

$('a#home').removeAttr('id');
Adding elements to the DOM
The append() method adds a new child element
  after the existing elements

There 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
Forms
The val() method sets and retrieves the value from
  a form field

It works exactly like the html() method
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();
  });
});
CSS

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

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

$("h1" ).css(
  {"color" : "red" ,
  "text-decoration" : "underline" }
);
CSS
However, 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" );
});
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');
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()
$('li').not(':even').css('background-color',
  'red');
Events
The .on() method attaches event handlers to the
  currently selected set of elements in the jQuery
  object
Event Names
Any event names can be used for the events argument
  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() method can be used to manually
  trigger an event
Selector
When a selector is provided, the event handler is
 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 Example

Delegated 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());
});
Event Handler
It 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
Event Data
If a data argument is provided to .on(), it is
  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
Event Data Example
$(“#button1").on(“touchstart",
  { name: “Ivano" }, greet);

$(“#button2").on(“touchstart",
  { name: “Andrea" }, greet);

function greet(event) {
  alert("Hello “ + event.data.name);
}
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
.off() and .one()

.off()
   to remove events bound with .on()



.one()
 one()
   to attach an event that runs only once and then
   removes itself
Shorthand methods
There are shorthand methods for some events that can be
  used to attach or trigger event handlers

.click()
.blur()
.focus()
.scroll()
.select()
.submit()
...
.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 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
Chaining

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

This means you can chain methods together:

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

Some methods return a different collection

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

$('#intro').css('color', '#cccccc').
find('a').addClass('highlighted').end().
find('em').css('color', 'red').end()
AJAX

Ajax 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 working

Basically, you can use AJAX to:
• load remote HTML
• get JSON data
Load remote HTML
load()
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');
Cross-site Scripting
Load JSON data
JSON is a lightweight alternative to XML, where data
  is structured as plain JavaScript objects
Load JSON Data




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
The Ajax() call
All 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
});
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() method
See http://api.jQuery.com/jQuery.ajax/
Effects

jQuery 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()
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
Roadmap

• Javascript References
• jQuery
• Useful Microframeworks
Useful Microframeworks

•   Zepto.js
•   Hammer.js
•   Underscore.js
•   Swipe.js
Zepto
    The only relevant downside of jQuery is about
                    PERFORMANCE

However,
1. It is not very noticeable in current class-A mobile
   devices
2. You can use mobile-suited alternatives to jQuery:
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 a
mini-jQuery
without support for
older browsers
Zepto Modules
Zepto Usage

Simply replace the reference to jQuery with the one to
  Zepto
Hammer.js

A 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
Using Hammer.js

You 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) {...};
Hammer Events

Every 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
Hammer Events
A 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.
Hammer Events
A 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:
Underscore.js
A 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
Swipe

Swipe is a lightweight mobile slider
Swipe Features

1:1 touch movement
   It tracks the position of the touch and moves the
   content exactly how the touch interact
      native feeling

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
Swipe Features
Rotation/resize adjustment
  When a user rotates the device, the slider resets to make
  sure the sliding elements are the right size

Variable width containers
  Swipe allows you to set a width to the container

Scroll prevention
  Swipe detects if you’re trying to scroll down the page or
  slide content left to right

Library agnostic
   Swipe is totally library independent (even from 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>

   a series of elements wrapped in two containers
Swipe Usage

Then you can attach a Swipe object to a DOM element

window.mySwipe = new Swipe(
  document.getElementById('sliderId'));
Swipe Usage

Optionally, 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
Swipe API
Functions 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)
References
http://www.microjs.com

http://jQuery.com

http://slidesha.re/IP5MJ5

More Related Content

What's hot (20)

PPT
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
PDF
jQuery - Chapter 1 - Introduction
WebStackAcademy
 
PDF
Introduction to Spring MVC
Richard Paul
 
PDF
Fast mobile web apps
Ivano Malavolta
 
PPTX
Jqueryppt (1)
AndreaSmile06
 
PDF
HTML5 & CSS3 refresher for mobile apps
Ivano Malavolta
 
PDF
[2015/2016] The REST architectural style
Ivano Malavolta
 
KEY
An Introduction to Ruby on Rails
Joe Fiorini
 
PPT
Jasig Rubyon Rails
Paul Pajo
 
PPT
jQuery and AJAX with Rails
Alan Hecht
 
PDF
jQuery and Rails: Best Friends Forever
stephskardal
 
PDF
Angular - Chapter 5 - Directives
WebStackAcademy
 
PPTX
Getting Started with Angular JS
Akshay Mathur
 
PDF
jQuery - Chapter 4 - DOM Handling
WebStackAcademy
 
PPTX
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
PPT
Spring MVC Basics
Bozhidar Bozhanov
 
PPTX
Angular JS
John Temoty Roca
 
PDF
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
jQuery - Chapter 1 - Introduction
WebStackAcademy
 
Introduction to Spring MVC
Richard Paul
 
Fast mobile web apps
Ivano Malavolta
 
Jqueryppt (1)
AndreaSmile06
 
HTML5 & CSS3 refresher for mobile apps
Ivano Malavolta
 
[2015/2016] The REST architectural style
Ivano Malavolta
 
An Introduction to Ruby on Rails
Joe Fiorini
 
Jasig Rubyon Rails
Paul Pajo
 
jQuery and AJAX with Rails
Alan Hecht
 
jQuery and Rails: Best Friends Forever
stephskardal
 
Angular - Chapter 5 - Directives
WebStackAcademy
 
Getting Started with Angular JS
Akshay Mathur
 
jQuery - Chapter 4 - DOM Handling
WebStackAcademy
 
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring MVC Basics
Bozhidar Bozhanov
 
Angular JS
John Temoty Roca
 
jQuery - Chapter 5 - Ajax
WebStackAcademy
 

Similar to jQuery (20)

PPTX
Web Development Introduction to jQuery
Laurence Svekis ✔
 
PPTX
jQuery basics for Beginners
Pooja Saxena
 
PDF
Introduction to jQuery
Zeeshan Khan
 
PDF
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
PPTX
Getting Started with jQuery
Akshay Mathur
 
PPTX
jQuery
Jon Erickson
 
PPTX
Web technologies-course 11.pptx
Stefan Oprea
 
KEY
Week 4 - jQuery + Ajax
baygross
 
PDF
Javascript libraries
Dumindu Pahalawatta
 
PPTX
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
PPTX
Unobtrusive javascript with jQuery
Angel Ruiz
 
PDF
fuser interface-development-using-jquery
Kostas Mavridis
 
PPTX
jQuery
Jay Poojara
 
PPTX
Introduction to Jquery
Ahmed Elharouny
 
PPTX
Unit-III_JQuery.pptx engineering subject for third year students
MARasheed3
 
PDF
The Dom Scripting Toolkit J Query
QConLondon2008
 
PDF
J query fundamentals
Attaporn Ninsuwan
 
KEY
User Interface Development with jQuery
colinbdclark
 
PPT
JavaScript JQUERY AJAX
Makarand Bhatambarekar
 
Web Development Introduction to jQuery
Laurence Svekis ✔
 
jQuery basics for Beginners
Pooja Saxena
 
Introduction to jQuery
Zeeshan Khan
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
Getting Started with jQuery
Akshay Mathur
 
jQuery
Jon Erickson
 
Web technologies-course 11.pptx
Stefan Oprea
 
Week 4 - jQuery + Ajax
baygross
 
Javascript libraries
Dumindu Pahalawatta
 
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
Unobtrusive javascript with jQuery
Angel Ruiz
 
fuser interface-development-using-jquery
Kostas Mavridis
 
jQuery
Jay Poojara
 
Introduction to Jquery
Ahmed Elharouny
 
Unit-III_JQuery.pptx engineering subject for third year students
MARasheed3
 
The Dom Scripting Toolkit J Query
QConLondon2008
 
J query fundamentals
Attaporn Ninsuwan
 
User Interface Development with jQuery
colinbdclark
 
JavaScript JQUERY AJAX
Makarand Bhatambarekar
 
Ad

More from Ivano Malavolta (20)

PDF
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
PDF
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Ivano Malavolta
 
PDF
The H2020 experience
Ivano Malavolta
 
PDF
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
Ivano Malavolta
 
PDF
Software sustainability and Green IT
Ivano Malavolta
 
PDF
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Ivano Malavolta
 
PDF
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
Ivano Malavolta
 
PDF
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Ivano Malavolta
 
PDF
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Ivano Malavolta
 
PDF
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Ivano Malavolta
 
PDF
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Ivano Malavolta
 
PDF
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Ivano Malavolta
 
PDF
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Ivano Malavolta
 
PDF
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Ivano Malavolta
 
PDF
Modeling and abstraction, software development process [Software Design] [Com...
Ivano Malavolta
 
PDF
[2017/2018] Agile development
Ivano Malavolta
 
PDF
Reconstructing microservice-based architectures
Ivano Malavolta
 
PDF
[2017/2018] AADL - Architecture Analysis and Design Language
Ivano Malavolta
 
PDF
[2017/2018] Architectural languages
Ivano Malavolta
 
PDF
[2017/2018] Introduction to Software Architecture
Ivano Malavolta
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Ivano Malavolta
 
The H2020 experience
Ivano Malavolta
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
Ivano Malavolta
 
Software sustainability and Green IT
Ivano Malavolta
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Ivano Malavolta
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
Ivano Malavolta
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Ivano Malavolta
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Ivano Malavolta
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Ivano Malavolta
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Ivano Malavolta
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Ivano Malavolta
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Ivano Malavolta
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Ivano Malavolta
 
Modeling and abstraction, software development process [Software Design] [Com...
Ivano Malavolta
 
[2017/2018] Agile development
Ivano Malavolta
 
Reconstructing microservice-based architectures
Ivano Malavolta
 
[2017/2018] AADL - Architecture Analysis and Design Language
Ivano Malavolta
 
[2017/2018] Architectural languages
Ivano Malavolta
 
[2017/2018] Introduction to Software Architecture
Ivano Malavolta
 
Ad

Recently uploaded (20)

PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Difference between write and update in odoo 18
Celine George
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 

jQuery

  • 1. jQuery Ivano Malavolta [email protected] http://www.di.univaq.it/malavolta
  • 2. Roadmap • Javascript References • jQuery • Useful Microframeworks
  • 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. Roadmap • Javascript References • jQuery • Useful Microframeworks
  • 5. jQuery A Javascript library for: • manipulating the DOM • adding effects • making Ajax requests
  • 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. jQuery Philosophy Focus on the interaction between JavaScript and HTML (Almost) every operation boils down to: • Find some stuff • Do something to it
  • 8. Loading jQuery You can grab the jQuery library from http://jQuery.com and link to the jQuery script directly <script type="text/javascript” charset="utf-8" src=“.js/lib/jQuery.js" > </script>
  • 9. 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");
  • 10. Document Ready $(document).ready(function(){ // Your code here }); jQuery has a simple statement that checks the document and waits until it's ready to be manipulated
  • 11. Callback Functions A callback is a function that 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() { // code } myCallBack is invoked when the '$.get' is done getting the page
  • 12. Inline Callback Functions A callback function can also be defined in-line $.get('myhtmlpage.html', function() { // code });
  • 13. Callback Functions with Parameters $.get('myhtmlpage.html', function() { myCallBack(‘Ivano’, ‘Malavolta’); }); function myCallBack(name, surname) { // code }
  • 14. jQuery Selectors You can use any CSS2 and CSS3 selectors to fetch elements from the DOM $(‘#nav') $('div#intro h2') $('#nav li.current a')
  • 15. 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')[1] $('div.section')[2]
  • 16. 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); });
  • 17. HTML elements You use the html() method to get and set the inner 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>');
  • 18. HTML attributes You use the attr() method to get and set the attribute of a specific HTML element var src = $('a#home').attr(‘href'); $('a#home').attr(‘href', './home.html'); $('a#home').attr({ 'href': './home.html', 'id': ‘home' }); $('a#home').removeAttr('id');
  • 19. Adding elements to the DOM The append() method adds a new child element after the existing elements There 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. Forms The val() method sets and retrieves the value from a form field It works exactly like the html() method
  • 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. CSS You can use the css() method to define styles on elements $("label" ).css("color" , "#f00" ); $("h1" ).css( {"color" : "red" , "text-decoration" : "underline" } );
  • 23. CSS However, 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. 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. 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() $('li').not(':even').css('background-color', 'red');
  • 26. Events The .on() method attaches event handlers to the currently selected set of elements in the jQuery object
  • 27. Event Names Any event names can be used for the events argument 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() method can be used to manually trigger an event
  • 28. Selector When a selector is provided, the event handler is 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
  • 29. Selector Example Delegated 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. Event Handler It 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. Event Data If a data argument is provided to .on(), it is 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
  • 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. 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. .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. Shorthand methods There are shorthand methods for some events that can be used to attach or trigger event handlers .click() .blur() .focus() .scroll() .select() .submit() ...
  • 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 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
  • 37. Chaining Most jQuery methods return another jQuery object, usually one representing the same collection This means you can chain methods together: $('div.section').hide().addClass('gone');
  • 38. Chains End Some methods return a different collection You 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. AJAX Ajax 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 working Basically, you can use AJAX to: • load remote HTML • get JSON data
  • 40. Load remote HTML load() 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');
  • 42. Load JSON data JSON is a lightweight alternative to XML, where data is structured as plain JavaScript objects
  • 43. Load JSON Data 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
  • 44. The Ajax() call All 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. 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() method See http://api.jQuery.com/jQuery.ajax/
  • 46. Effects jQuery 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. 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. Roadmap • Javascript References • jQuery • Useful Microframeworks
  • 49. Useful Microframeworks • Zepto.js • Hammer.js • Underscore.js • Swipe.js
  • 50. Zepto The only relevant downside of jQuery is about PERFORMANCE However, 1. It is not very noticeable in current class-A mobile devices 2. You can use mobile-suited alternatives to jQuery:
  • 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 a mini-jQuery without support for older browsers
  • 53. Zepto Usage Simply replace the reference to jQuery with the one to Zepto
  • 54. Hammer.js A 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. Using Hammer.js You 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. Hammer Events Every 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. Hammer Events A 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. Hammer Events A 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. Underscore.js A 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. Swipe Swipe is a lightweight mobile slider
  • 61. Swipe Features 1:1 touch movement It tracks the position of the touch and moves the content exactly how the touch interact native feeling 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
  • 62. Swipe Features Rotation/resize adjustment When a user rotates the device, the slider resets to make sure the sliding elements are the right size Variable width containers Swipe allows you to set a width to the container Scroll prevention Swipe detects if you’re trying to scroll down the page or slide content left to right Library agnostic Swipe is totally library independent (even from jQuery)
  • 63. 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> a series of elements wrapped in two containers
  • 64. Swipe Usage Then you can attach a Swipe object to a DOM element window.mySwipe = new Swipe( document.getElementById('sliderId'));
  • 65. Swipe Usage Optionally, 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. Swipe API Functions 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)