SlideShare a Scribd company logo
jQuery BasicjQuery Basic
The Way to JavaScript and RichThe Way to JavaScript and Rich
Internet ApplicationsInternet Applications
Introduction to jQueryIntroduction to jQuery
• Developed by John Resig at Rochester Institute of TechnologyDeveloped by John Resig at Rochester Institute of Technology
• ““jQueryjQuery is a lightweightis a lightweight JavaScript libraryJavaScript library that emphasizesthat emphasizes
interaction betweeninteraction between JavaScriptJavaScript andand HTMLHTML. It was released in. It was released in
January 2006 atJanuary 2006 at BarCampBarCamp NYC byNYC by John ResigJohn Resig.”.”
• ““jQuery isjQuery is free, open sourcefree, open source
• Current version is 2.1.4Current version is 2.1.4
Introduction to jQueryIntroduction to jQuery
• Why do I want itWhy do I want it
– Rich Internet Applications (RIA)Rich Internet Applications (RIA)
– Dynamic HTML (DHTML)Dynamic HTML (DHTML)
• How do I get itHow do I get it
– www.jquery.comwww.jquery.com
• How can I learn itHow can I learn it
– jQuery in ActionjQuery in Action by Bibeault & Katz, Manningby Bibeault & Katz, Manning
– jQuery Visual Quickstart GuidejQuery Visual Quickstart Guide by Holzner, Peachpitby Holzner, Peachpit
– www.jquery.comwww.jquery.com
– docs.jquery.comdocs.jquery.com
– www.visualjquery.comwww.visualjquery.com
– www.Jqueryfordesigners.comwww.Jqueryfordesigners.com
– www.gscottolson.com/weblog/ - cheat sheetwww.gscottolson.com/weblog/ - cheat sheet
– www.javascripttoolbox.com/jquerywww.javascripttoolbox.com/jquery
Plan for the 4 sessionsPlan for the 4 sessions
• Class I – Introduction, installation, ReadyClass I – Introduction, installation, Ready
function, DOM, Selecting and Formattingfunction, DOM, Selecting and Formatting
web page elementsweb page elements
• Class II – Events and AnimationsClass II – Events and Animations
• Class III – jQuery Plugin librariesClass III – jQuery Plugin libraries
• Class IV – AJAX with PHPClass IV – AJAX with PHP
Introduction to jQueryIntroduction to jQuery
• Installation – You just download theInstallation – You just download the
jquery-1.3.2.js file and put it in yourjquery-1.3.2.js file and put it in your
website folderwebsite folder
– Can access via URLCan access via URL
What jQuery DoesWhat jQuery Does
• ““Unobtrusive” JavaScript – separation ofUnobtrusive” JavaScript – separation of
behaviorbehavior from structurefrom structure
• CSS – separation ofCSS – separation of stylestyle from structurefrom structure
• Allows adding JavaScript to your web pagesAllows adding JavaScript to your web pages
• Advantages overAdvantages over justjust JavaScriptJavaScript
– Much easier to useMuch easier to use
– Eliminates cross-browser problemsEliminates cross-browser problems
• HTML to CSS to DHTMLHTML to CSS to DHTML
5 Things jQuery Provides5 Things jQuery Provides
• Select DOM (Document Object Model) elementsSelect DOM (Document Object Model) elements
on a page – one element or a group of themon a page – one element or a group of them
• Set properties of DOM elements, in groupsSet properties of DOM elements, in groups
(“Find something, do something with it”)(“Find something, do something with it”)
• Creates, deletes, shows, hides DOM elementsCreates, deletes, shows, hides DOM elements
• Defines event behavior on a page (click, mouseDefines event behavior on a page (click, mouse
movement, dynamic styles, animations, dynamicmovement, dynamic styles, animations, dynamic
content)content)
• AJAX callsAJAX calls
The DOMThe DOM
• Document Object ModelDocument Object Model
• jQuery is “DOM scripting”jQuery is “DOM scripting”
• Heirarchal structure of a web pageHeirarchal structure of a web page
• You can add and subtract DOM elementsYou can add and subtract DOM elements
• You can change the properties andYou can change the properties and
contents of DOM elementscontents of DOM elements
The DOMThe DOM
• ““TheThe Document Object ModelDocument Object Model ((DOMDOM) is a cross-platform and) is a cross-platform and
language-independent convention for representing and interactinglanguage-independent convention for representing and interacting
with objects in HTML, XHTML and XML documents. Aspects of thewith objects in HTML, XHTML and XML documents. Aspects of the
DOM (such as its "Elements") may be addressed and manipulatedDOM (such as its "Elements") may be addressed and manipulated
within the syntax of the programming language in use.” Wikipediawithin the syntax of the programming language in use.” Wikipedia
The jQuery FunctionThe jQuery Function
• jQuery() = $()jQuery() = $()
• $(function)$(function) The “Ready” handlerThe “Ready” handler
• $(‘selector’)$(‘selector’) Element selector expressionElement selector expression
• $(element)$(element) Specify element(s) directlySpecify element(s) directly
• $(‘HTML’)$(‘HTML’) HTML creationHTML creation
• $.function()$.function() Execute a jQuery functionExecute a jQuery function
• $.fn.myfunc(){}$.fn.myfunc(){} Create jQuery functionCreate jQuery function
Tutorial 1 – The Ready FunctionTutorial 1 – The Ready Function
• Set up a basic HTML page and add jQuerySet up a basic HTML page and add jQuery
• Create a “ready” functionCreate a “ready” function
• Call a functionCall a function
• 5 ways to specify the ready function5 ways to specify the ready function
– jquery(document).ready(function(){…};);jquery(document).ready(function(){…};);
– jquery().ready(function(){…};)jquery().ready(function(){…};)
– jquery(function(){…};)jquery(function(){…};)
– jquery(dofunc);jquery(dofunc);
– $(dofunc);$(dofunc);
Tutorial 2 – Selecting ElementsTutorial 2 – Selecting Elements
Creating a “wrapped set”Creating a “wrapped set”
• $(selector)$(selector)
• selector:selector:
– $(‘#id’)$(‘#id’) id of elementid of element
– $(‘p’)$(‘p’) tag nametag name
– $(‘.class’)$(‘.class’) CSS classCSS class
– $(‘p.class’)$(‘p.class’) <p> elements having the CSS class<p> elements having the CSS class
– $(‘p:first’)$(‘p:first’) $(‘p:last’)$(‘p:last’) $(‘p:odd’)$(‘p:odd’) $(‘p:even’)$(‘p:even’)
– $(‘p:eq(2)’)$(‘p:eq(2)’) gets the 2gets the 2ndnd
<p> element (1 based)<p> element (1 based)
– $(‘p’)[1]$(‘p’)[1] gets the 2gets the 2ndnd
<p> element (0 based)<p> element (0 based)
– $(‘p:nth-child(3))$(‘p:nth-child(3)) gets the 3gets the 3rdrd
<p> element of the parent. n=even, odd too.<p> element of the parent. n=even, odd too.
– $(‘p:nth-child(5n+1)’)$(‘p:nth-child(5n+1)’) gets the 1gets the 1stst
element after every 5th oneelement after every 5th one
– $(‘p a’)$(‘p a’) Selects all <a> elements inside <p> elementsSelects all <a> elements inside <p> elements
– $(‘p>a’)$(‘p>a’) <a> elements, direct child of a <p><a> elements, direct child of a <p>
– $(‘p+a’)$(‘p+a’) <a> elements, directly following a <p><a> elements, directly following a <p>
– $(‘p, a’)$(‘p, a’) <p> and <a> elements<p> and <a> elements
– $(‘li:has(ul)’)$(‘li:has(ul)’) <li> elements that have at least one <ul> descendent<li> elements that have at least one <ul> descendent
– $(‘:not(p)’)$(‘:not(p)’) all elements but <p> elementsall elements but <p> elements
– $(‘p:hidden’)$(‘p:hidden’) only <p> elements that are hiddenonly <p> elements that are hidden
– $(‘p:empty’)$(‘p:empty’) <p> elements that have no child elements<p> elements that have no child elements
Selecting Elements, cont.Selecting Elements, cont.
• $(‘img’[alt])$(‘img’[alt]) <img> elements having an alt attribute<img> elements having an alt attribute
• $(‘a’[href^=http://])$(‘a’[href^=http://]) <a> elements with an href attribute<a> elements with an href attribute
starting with ‘http://’starting with ‘http://’
• $(‘a’[href$=.pdf])$(‘a’[href$=.pdf]) <a> elements with an href attribute<a> elements with an href attribute
ending with ‘.pdf’ending with ‘.pdf’
• $(‘a’[href*=ntpcug])$(‘a’[href*=ntpcug]) <a> elements with an href attriute<a> elements with an href attriute
containing ‘ntpcug’containing ‘ntpcug’
Useful jQuery FunctionsUseful jQuery Functions
• .each().each() iterate over the setiterate over the set
• .size().size() number of elements in setnumber of elements in set
• .end().end() reverts to the previous setreverts to the previous set
• .get(n).get(n) get just the nth element (0 based)get just the nth element (0 based)
• .eq(n).eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)get just the nth element (0 based) also .lt(n) & .gt(n)
• .slice(n,m).slice(n,m) gets only nth to (m-1)th elementsgets only nth to (m-1)th elements
• .not(‘p’).not(‘p’) don’t include ‘p’ elements in setdon’t include ‘p’ elements in set
• .add(‘p’).add(‘p’) add <p> elements to setadd <p> elements to set
• .remove().remove() removes all the elements from the page DOMremoves all the elements from the page DOM
• .empty().empty() removes the contents of all the elementsremoves the contents of all the elements
• .filter(fn/sel).filter(fn/sel) selects elements where the func returns true or selselects elements where the func returns true or sel
• .find(selector).find(selector) selects elements meeting the selector criteriaselects elements meeting the selector criteria
• .parent().parent() returns the parent of each element in setreturns the parent of each element in set
• .children().children() returns all the children of each element in setreturns all the children of each element in set
• .next().next() gets next element of each element in setgets next element of each element in set
• .prev().prev() gets previous element of each element in setgets previous element of each element in set
• .siblings().siblings() gets all the siblings of the current elementgets all the siblings of the current element
Tutorial 3 – Formatting ElementsTutorial 3 – Formatting Elements
• .css(property, value).css(property, value)
• .html().html()
• .val().val() (form elements)(form elements)
• .text().text()
• .addClass(‘class’).addClass(‘class’)
• .removeClass(‘class’).removeClass(‘class’)
Tutorial 4 – Add Page ElementsTutorial 4 – Add Page Elements
• $(‘#target’).before(‘<p>Inserted before #target</p>’);$(‘#target’).before(‘<p>Inserted before #target</p>’);
• $(‘#target’).after(‘<p>This is added after #target</p>’);$(‘#target’).after(‘<p>This is added after #target</p>’);
• $(‘#target’).append(‘<p>Goes inside #target, at end</p>’);$(‘#target’).append(‘<p>Goes inside #target, at end</p>’);
• $(‘#target’).wrap(‘<div></div>’);$(‘#target’).wrap(‘<div></div>’);
Adding EventsAdding Events
• Mouseover events – bind, hover, toggleMouseover events – bind, hover, toggle
• Button click eventsButton click events
Basic Syntax of Event BindingBasic Syntax of Event Binding
• $(‘img’).bind(‘click’,function(event){alert(‘Howdy’;});$(‘img’).bind(‘click’,function(event){alert(‘Howdy’;});
• $(‘img’).bind(‘click’,imgclick(event));$(‘img’).bind(‘click’,imgclick(event));
– Allows unbinding the functionAllows unbinding the function
• $(‘img’).unbind(‘click’,imgclick());$(‘img’).unbind(‘click’,imgclick());
• $(‘img’).unbind(‘click’);$(‘img’).unbind(‘click’);
• $(‘img’).one(‘click’,imgclick(event));$(‘img’).one(‘click’,imgclick(event));
– Only works onceOnly works once
• $(‘img’).click(imgclick);$(‘img’).click(imgclick);
• $(‘img’).toggle(click1, click2);$(‘img’).toggle(click1, click2);
• $(‘img’).hover(mouseover, mouseout);$(‘img’).hover(mouseover, mouseout);
Shortcut Event BindingShortcut Event Binding
• .click(func).click(func)
• .submit(func).submit(func)
• .dblclick(func).dblclick(func)
• .mouseover(func).mouseover(func)
• .mouseout(func).mouseout(func)
• .select(func).select(func)
Useful Event FunctionsUseful Event Functions
• .hide().hide() display:truedisplay:true
• .show().show() display:nonedisplay:none
• .toggle(func1, func2) first click calls func1, next.toggle(func1, func2) first click calls func1, next
click executes func2click executes func2
• .hover(over, out).hover(over, out) mouseover, mouseoutmouseover, mouseout
Jquery noConflictJquery noConflict
<script type="text/javascript"><script type="text/javascript">
var $j = jQuery.noConflict();var $j = jQuery.noConflict();
</script></script>
Replace all $ or jQuery by $j.Replace all $ or jQuery by $j.
Before : $(‘p’).text();Before : $(‘p’).text();
After: $j(‘p’).text();After: $j(‘p’).text();
AJAXAJAX
• What is AJAXWhat is AJAX
• The basic AJAX function –The basic AJAX function –
XMLHttpRequestXMLHttpRequest
• Initiating a requestInitiating a request
• Getting the responseGetting the response
jQuery - AJAX IntroductionjQuery - AJAX Introduction
• AJAX is the art of exchanging data with aAJAX is the art of exchanging data with a
server, and updating parts of a web page -server, and updating parts of a web page -
without reloading the whole page.without reloading the whole page.
• Stand for “Asynchronous JavaScript andStand for “Asynchronous JavaScript and
XML”XML”
Ajax Sending GET/POSTAjax Sending GET/POST
requestsrequests
  $(“div”).load(“content.htm”);$(“div”).load(“content.htm”);
// passing parameters// passing parameters
$(“#content”).load(“getcontent.php”,$(“#content”).load(“getcontent.php”,
{{
““id”:”33”,id”:”33”,
“type”:”main”“type”:”main”
});});
AJAX basic functionAJAX basic function
  $.ajax({$.ajax({
                                        url : "result.php",url : "result.php",
                                        type : "post",type : "post",
                                      dateType:"text",dateType:"text",
                                        data : {data : {
                                                  prefecture_id: $('# prefecture_id ').val()prefecture_id: $('# prefecture_id ').val()
                                        },},
                                        success : function (result){success : function (result){
                                                $('#result').html(result);$('#result').html(result);
                                        }}
                              });});

More Related Content

PPTX
JQuery
DevTalk
 
ODP
Jquery for Beginners
Mohd Abdul Baquee
 
PDF
jQuery Rescue Adventure
Allegient
 
PPTX
Jquery
Zoya Shaikh
 
PPTX
jQuery Fundamentals
Gil Fink
 
PDF
jQuery Essentials
Marc Grabanski
 
PPTX
JQuery
SelmanJagxhiu
 
PPTX
Jquery-overview
Isfand yar Khan
 
JQuery
DevTalk
 
Jquery for Beginners
Mohd Abdul Baquee
 
jQuery Rescue Adventure
Allegient
 
Jquery
Zoya Shaikh
 
jQuery Fundamentals
Gil Fink
 
jQuery Essentials
Marc Grabanski
 
Jquery-overview
Isfand yar Khan
 

What's hot (20)

PDF
Learning jQuery made exciting in an interactive session by one of our team me...
Thinqloud
 
PPTX
jQuery
Dileep Mishra
 
PPTX
Iniciando com jquery
Danilo Sousa
 
PPTX
jQuery quick tuts
Nasa Vietnam
 
PPT
JQuery introduction
NexThoughts Technologies
 
PDF
citigroup January 13, 2006 - Reformatted Quarterly Financial Data Supplement...
QuarterlyEarningsReports
 
PPTX
jQuery, CSS3 and ColdFusion
Denard Springle IV
 
PPT
jQuery
Mostafa Bayomi
 
PDF
Learning jQuery in 30 minutes
Simon Willison
 
ODP
Introduction to jQuery
manugoel2003
 
PDF
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
PDF
Write Less Do More
Remy Sharp
 
PDF
jQuery Essentials
Bedis ElAchèche
 
KEY
Advanced Django ORM techniques
Daniel Roseman
 
PDF
jQuery - Introdução
Gustavo Dutra
 
PDF
Prototype & jQuery
Remy Sharp
 
PDF
appengine java night #1
Shinichi Ogawa
 
PPTX
Prototype Framework
Julie Iskander
 
Learning jQuery made exciting in an interactive session by one of our team me...
Thinqloud
 
Iniciando com jquery
Danilo Sousa
 
jQuery quick tuts
Nasa Vietnam
 
JQuery introduction
NexThoughts Technologies
 
citigroup January 13, 2006 - Reformatted Quarterly Financial Data Supplement...
QuarterlyEarningsReports
 
jQuery, CSS3 and ColdFusion
Denard Springle IV
 
Learning jQuery in 30 minutes
Simon Willison
 
Introduction to jQuery
manugoel2003
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
Write Less Do More
Remy Sharp
 
jQuery Essentials
Bedis ElAchèche
 
Advanced Django ORM techniques
Daniel Roseman
 
jQuery - Introdução
Gustavo Dutra
 
Prototype & jQuery
Remy Sharp
 
appengine java night #1
Shinichi Ogawa
 
Prototype Framework
Julie Iskander
 
Ad

Viewers also liked (6)

PDF
Javascript basic course
Tran Khoa
 
PPT
Basic Javascript
Bunlong Van
 
PPT
Js ppt
Rakhi Thota
 
PDF
reveal.js 3.0.0
Hakim El Hattab
 
PDF
JavaScript Programming
Sehwan Noh
 
PDF
Unobtrusive JavaScript with jQuery
Simon Willison
 
Javascript basic course
Tran Khoa
 
Basic Javascript
Bunlong Van
 
Js ppt
Rakhi Thota
 
reveal.js 3.0.0
Hakim El Hattab
 
JavaScript Programming
Sehwan Noh
 
Unobtrusive JavaScript with jQuery
Simon Willison
 
Ad

Similar to J query introduction (20)

PPT
jQuery Introduction/ jquery basic concept
MuhammadJameel83
 
PDF
Introduction to jQuery
Zeeshan Khan
 
PPTX
Introduction to jQuery
Gunjan Kumar
 
PDF
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
PPTX
Web technologies-course 11.pptx
Stefan Oprea
 
KEY
jQuery Selectors
jQuerySlideCasts
 
PPTX
Getting Started with jQuery
Laila Buncab
 
PPTX
jQuery
Jay Poojara
 
PPT
J query module1
Srivatsan Krishnamachari
 
PPTX
JQuery
Jacob Nelson
 
PPTX
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
PDF
Introduction to jQuery
Seble Nigussie
 
PPTX
Jquery
Pankaj Srivastava
 
PPTX
How to increase Performance of Web Application using JQuery
kolkatageeks
 
PPTX
jQuery
Julie Iskander
 
PPTX
Getting started with jQuery
Gill Cleeren
 
PPTX
SPTechCon - Share point and jquery essentials
Mark Rackley
 
PPTX
jQuery basics for Beginners
Pooja Saxena
 
jQuery Introduction/ jquery basic concept
MuhammadJameel83
 
Introduction to jQuery
Zeeshan Khan
 
Introduction to jQuery
Gunjan Kumar
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
Web technologies-course 11.pptx
Stefan Oprea
 
jQuery Selectors
jQuerySlideCasts
 
Getting Started with jQuery
Laila Buncab
 
jQuery
Jay Poojara
 
J query module1
Srivatsan Krishnamachari
 
JQuery
Jacob Nelson
 
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
Introduction to jQuery
Seble Nigussie
 
How to increase Performance of Web Application using JQuery
kolkatageeks
 
Getting started with jQuery
Gill Cleeren
 
SPTechCon - Share point and jquery essentials
Mark Rackley
 
jQuery basics for Beginners
Pooja Saxena
 

Recently uploaded (20)

PDF
Immersive experiences: what Pharo users do!
ESUG
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
Immersive experiences: what Pharo users do!
ESUG
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
Presentation about variables and constant.pptx
safalsingh810
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
Exploring AI Agents in Process Industries
amoreira6
 
Role Of Python In Programing Language.pptx
jaykoshti048
 

J query introduction

  • 1. jQuery BasicjQuery Basic The Way to JavaScript and RichThe Way to JavaScript and Rich Internet ApplicationsInternet Applications
  • 2. Introduction to jQueryIntroduction to jQuery • Developed by John Resig at Rochester Institute of TechnologyDeveloped by John Resig at Rochester Institute of Technology • ““jQueryjQuery is a lightweightis a lightweight JavaScript libraryJavaScript library that emphasizesthat emphasizes interaction betweeninteraction between JavaScriptJavaScript andand HTMLHTML. It was released in. It was released in January 2006 atJanuary 2006 at BarCampBarCamp NYC byNYC by John ResigJohn Resig.”.” • ““jQuery isjQuery is free, open sourcefree, open source • Current version is 2.1.4Current version is 2.1.4
  • 3. Introduction to jQueryIntroduction to jQuery • Why do I want itWhy do I want it – Rich Internet Applications (RIA)Rich Internet Applications (RIA) – Dynamic HTML (DHTML)Dynamic HTML (DHTML) • How do I get itHow do I get it – www.jquery.comwww.jquery.com • How can I learn itHow can I learn it – jQuery in ActionjQuery in Action by Bibeault & Katz, Manningby Bibeault & Katz, Manning – jQuery Visual Quickstart GuidejQuery Visual Quickstart Guide by Holzner, Peachpitby Holzner, Peachpit – www.jquery.comwww.jquery.com – docs.jquery.comdocs.jquery.com – www.visualjquery.comwww.visualjquery.com – www.Jqueryfordesigners.comwww.Jqueryfordesigners.com – www.gscottolson.com/weblog/ - cheat sheetwww.gscottolson.com/weblog/ - cheat sheet – www.javascripttoolbox.com/jquerywww.javascripttoolbox.com/jquery
  • 4. Plan for the 4 sessionsPlan for the 4 sessions • Class I – Introduction, installation, ReadyClass I – Introduction, installation, Ready function, DOM, Selecting and Formattingfunction, DOM, Selecting and Formatting web page elementsweb page elements • Class II – Events and AnimationsClass II – Events and Animations • Class III – jQuery Plugin librariesClass III – jQuery Plugin libraries • Class IV – AJAX with PHPClass IV – AJAX with PHP
  • 5. Introduction to jQueryIntroduction to jQuery • Installation – You just download theInstallation – You just download the jquery-1.3.2.js file and put it in yourjquery-1.3.2.js file and put it in your website folderwebsite folder – Can access via URLCan access via URL
  • 6. What jQuery DoesWhat jQuery Does • ““Unobtrusive” JavaScript – separation ofUnobtrusive” JavaScript – separation of behaviorbehavior from structurefrom structure • CSS – separation ofCSS – separation of stylestyle from structurefrom structure • Allows adding JavaScript to your web pagesAllows adding JavaScript to your web pages • Advantages overAdvantages over justjust JavaScriptJavaScript – Much easier to useMuch easier to use – Eliminates cross-browser problemsEliminates cross-browser problems • HTML to CSS to DHTMLHTML to CSS to DHTML
  • 7. 5 Things jQuery Provides5 Things jQuery Provides • Select DOM (Document Object Model) elementsSelect DOM (Document Object Model) elements on a page – one element or a group of themon a page – one element or a group of them • Set properties of DOM elements, in groupsSet properties of DOM elements, in groups (“Find something, do something with it”)(“Find something, do something with it”) • Creates, deletes, shows, hides DOM elementsCreates, deletes, shows, hides DOM elements • Defines event behavior on a page (click, mouseDefines event behavior on a page (click, mouse movement, dynamic styles, animations, dynamicmovement, dynamic styles, animations, dynamic content)content) • AJAX callsAJAX calls
  • 8. The DOMThe DOM • Document Object ModelDocument Object Model • jQuery is “DOM scripting”jQuery is “DOM scripting” • Heirarchal structure of a web pageHeirarchal structure of a web page • You can add and subtract DOM elementsYou can add and subtract DOM elements • You can change the properties andYou can change the properties and contents of DOM elementscontents of DOM elements
  • 9. The DOMThe DOM • ““TheThe Document Object ModelDocument Object Model ((DOMDOM) is a cross-platform and) is a cross-platform and language-independent convention for representing and interactinglanguage-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of thewith objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulatedDOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use.” Wikipediawithin the syntax of the programming language in use.” Wikipedia
  • 10. The jQuery FunctionThe jQuery Function • jQuery() = $()jQuery() = $() • $(function)$(function) The “Ready” handlerThe “Ready” handler • $(‘selector’)$(‘selector’) Element selector expressionElement selector expression • $(element)$(element) Specify element(s) directlySpecify element(s) directly • $(‘HTML’)$(‘HTML’) HTML creationHTML creation • $.function()$.function() Execute a jQuery functionExecute a jQuery function • $.fn.myfunc(){}$.fn.myfunc(){} Create jQuery functionCreate jQuery function
  • 11. Tutorial 1 – The Ready FunctionTutorial 1 – The Ready Function • Set up a basic HTML page and add jQuerySet up a basic HTML page and add jQuery • Create a “ready” functionCreate a “ready” function • Call a functionCall a function • 5 ways to specify the ready function5 ways to specify the ready function – jquery(document).ready(function(){…};);jquery(document).ready(function(){…};); – jquery().ready(function(){…};)jquery().ready(function(){…};) – jquery(function(){…};)jquery(function(){…};) – jquery(dofunc);jquery(dofunc); – $(dofunc);$(dofunc);
  • 12. Tutorial 2 – Selecting ElementsTutorial 2 – Selecting Elements Creating a “wrapped set”Creating a “wrapped set” • $(selector)$(selector) • selector:selector: – $(‘#id’)$(‘#id’) id of elementid of element – $(‘p’)$(‘p’) tag nametag name – $(‘.class’)$(‘.class’) CSS classCSS class – $(‘p.class’)$(‘p.class’) <p> elements having the CSS class<p> elements having the CSS class – $(‘p:first’)$(‘p:first’) $(‘p:last’)$(‘p:last’) $(‘p:odd’)$(‘p:odd’) $(‘p:even’)$(‘p:even’) – $(‘p:eq(2)’)$(‘p:eq(2)’) gets the 2gets the 2ndnd <p> element (1 based)<p> element (1 based) – $(‘p’)[1]$(‘p’)[1] gets the 2gets the 2ndnd <p> element (0 based)<p> element (0 based) – $(‘p:nth-child(3))$(‘p:nth-child(3)) gets the 3gets the 3rdrd <p> element of the parent. n=even, odd too.<p> element of the parent. n=even, odd too. – $(‘p:nth-child(5n+1)’)$(‘p:nth-child(5n+1)’) gets the 1gets the 1stst element after every 5th oneelement after every 5th one – $(‘p a’)$(‘p a’) Selects all <a> elements inside <p> elementsSelects all <a> elements inside <p> elements – $(‘p>a’)$(‘p>a’) <a> elements, direct child of a <p><a> elements, direct child of a <p> – $(‘p+a’)$(‘p+a’) <a> elements, directly following a <p><a> elements, directly following a <p> – $(‘p, a’)$(‘p, a’) <p> and <a> elements<p> and <a> elements – $(‘li:has(ul)’)$(‘li:has(ul)’) <li> elements that have at least one <ul> descendent<li> elements that have at least one <ul> descendent – $(‘:not(p)’)$(‘:not(p)’) all elements but <p> elementsall elements but <p> elements – $(‘p:hidden’)$(‘p:hidden’) only <p> elements that are hiddenonly <p> elements that are hidden – $(‘p:empty’)$(‘p:empty’) <p> elements that have no child elements<p> elements that have no child elements
  • 13. Selecting Elements, cont.Selecting Elements, cont. • $(‘img’[alt])$(‘img’[alt]) <img> elements having an alt attribute<img> elements having an alt attribute • $(‘a’[href^=http://])$(‘a’[href^=http://]) <a> elements with an href attribute<a> elements with an href attribute starting with ‘http://’starting with ‘http://’ • $(‘a’[href$=.pdf])$(‘a’[href$=.pdf]) <a> elements with an href attribute<a> elements with an href attribute ending with ‘.pdf’ending with ‘.pdf’ • $(‘a’[href*=ntpcug])$(‘a’[href*=ntpcug]) <a> elements with an href attriute<a> elements with an href attriute containing ‘ntpcug’containing ‘ntpcug’
  • 14. Useful jQuery FunctionsUseful jQuery Functions • .each().each() iterate over the setiterate over the set • .size().size() number of elements in setnumber of elements in set • .end().end() reverts to the previous setreverts to the previous set • .get(n).get(n) get just the nth element (0 based)get just the nth element (0 based) • .eq(n).eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)get just the nth element (0 based) also .lt(n) & .gt(n) • .slice(n,m).slice(n,m) gets only nth to (m-1)th elementsgets only nth to (m-1)th elements • .not(‘p’).not(‘p’) don’t include ‘p’ elements in setdon’t include ‘p’ elements in set • .add(‘p’).add(‘p’) add <p> elements to setadd <p> elements to set • .remove().remove() removes all the elements from the page DOMremoves all the elements from the page DOM • .empty().empty() removes the contents of all the elementsremoves the contents of all the elements • .filter(fn/sel).filter(fn/sel) selects elements where the func returns true or selselects elements where the func returns true or sel • .find(selector).find(selector) selects elements meeting the selector criteriaselects elements meeting the selector criteria • .parent().parent() returns the parent of each element in setreturns the parent of each element in set • .children().children() returns all the children of each element in setreturns all the children of each element in set • .next().next() gets next element of each element in setgets next element of each element in set • .prev().prev() gets previous element of each element in setgets previous element of each element in set • .siblings().siblings() gets all the siblings of the current elementgets all the siblings of the current element
  • 15. Tutorial 3 – Formatting ElementsTutorial 3 – Formatting Elements • .css(property, value).css(property, value) • .html().html() • .val().val() (form elements)(form elements) • .text().text() • .addClass(‘class’).addClass(‘class’) • .removeClass(‘class’).removeClass(‘class’)
  • 16. Tutorial 4 – Add Page ElementsTutorial 4 – Add Page Elements • $(‘#target’).before(‘<p>Inserted before #target</p>’);$(‘#target’).before(‘<p>Inserted before #target</p>’); • $(‘#target’).after(‘<p>This is added after #target</p>’);$(‘#target’).after(‘<p>This is added after #target</p>’); • $(‘#target’).append(‘<p>Goes inside #target, at end</p>’);$(‘#target’).append(‘<p>Goes inside #target, at end</p>’); • $(‘#target’).wrap(‘<div></div>’);$(‘#target’).wrap(‘<div></div>’);
  • 17. Adding EventsAdding Events • Mouseover events – bind, hover, toggleMouseover events – bind, hover, toggle • Button click eventsButton click events
  • 18. Basic Syntax of Event BindingBasic Syntax of Event Binding • $(‘img’).bind(‘click’,function(event){alert(‘Howdy’;});$(‘img’).bind(‘click’,function(event){alert(‘Howdy’;}); • $(‘img’).bind(‘click’,imgclick(event));$(‘img’).bind(‘click’,imgclick(event)); – Allows unbinding the functionAllows unbinding the function • $(‘img’).unbind(‘click’,imgclick());$(‘img’).unbind(‘click’,imgclick()); • $(‘img’).unbind(‘click’);$(‘img’).unbind(‘click’); • $(‘img’).one(‘click’,imgclick(event));$(‘img’).one(‘click’,imgclick(event)); – Only works onceOnly works once • $(‘img’).click(imgclick);$(‘img’).click(imgclick); • $(‘img’).toggle(click1, click2);$(‘img’).toggle(click1, click2); • $(‘img’).hover(mouseover, mouseout);$(‘img’).hover(mouseover, mouseout);
  • 19. Shortcut Event BindingShortcut Event Binding • .click(func).click(func) • .submit(func).submit(func) • .dblclick(func).dblclick(func) • .mouseover(func).mouseover(func) • .mouseout(func).mouseout(func) • .select(func).select(func)
  • 20. Useful Event FunctionsUseful Event Functions • .hide().hide() display:truedisplay:true • .show().show() display:nonedisplay:none • .toggle(func1, func2) first click calls func1, next.toggle(func1, func2) first click calls func1, next click executes func2click executes func2 • .hover(over, out).hover(over, out) mouseover, mouseoutmouseover, mouseout
  • 21. Jquery noConflictJquery noConflict <script type="text/javascript"><script type="text/javascript"> var $j = jQuery.noConflict();var $j = jQuery.noConflict(); </script></script> Replace all $ or jQuery by $j.Replace all $ or jQuery by $j. Before : $(‘p’).text();Before : $(‘p’).text(); After: $j(‘p’).text();After: $j(‘p’).text();
  • 22. AJAXAJAX • What is AJAXWhat is AJAX • The basic AJAX function –The basic AJAX function – XMLHttpRequestXMLHttpRequest • Initiating a requestInitiating a request • Getting the responseGetting the response
  • 23. jQuery - AJAX IntroductionjQuery - AJAX Introduction • AJAX is the art of exchanging data with aAJAX is the art of exchanging data with a server, and updating parts of a web page -server, and updating parts of a web page - without reloading the whole page.without reloading the whole page. • Stand for “Asynchronous JavaScript andStand for “Asynchronous JavaScript and XML”XML”
  • 24. Ajax Sending GET/POSTAjax Sending GET/POST requestsrequests   $(“div”).load(“content.htm”);$(“div”).load(“content.htm”); // passing parameters// passing parameters $(“#content”).load(“getcontent.php”,$(“#content”).load(“getcontent.php”, {{ ““id”:”33”,id”:”33”, “type”:”main”“type”:”main” });});
  • 25. AJAX basic functionAJAX basic function   $.ajax({$.ajax({                                         url : "result.php",url : "result.php",                                         type : "post",type : "post",                                       dateType:"text",dateType:"text",                                         data : {data : {                                                   prefecture_id: $('# prefecture_id ').val()prefecture_id: $('# prefecture_id ').val()                                         },},                                         success : function (result){success : function (result){                                                 $('#result').html(result);$('#result').html(result);                                         }}                               });});