SlideShare a Scribd company logo
jQueryWrites less, Do MoreCh. Vishwa MohanFreelance Software Consultant &Corporate Trainer
Table of ContentsjQuery IntroductionjQuery BasicsjQuery CoreEventsAnimationAJAXPlugins
jQuery Introduction
Evolution
With AJAX .  .  .JavaScript has become essential to current web page development, but.. JavaScript is not a good language design.JavaScript has become bloatedDOM Navigation
Browser differencesWriting JavaScript code is tedious, time-consuming and error prone.
Why you might want to use jQueryjQuery makes writing Javascript much easier. DOM Navigation (CSS-like syntax)
Apply methods to sets of DOM elements.
Builder model (chain method calls)
Extensible and there are tons of libraries
Handles most of browser differences so you don’t have to Server provides datajQuery on client provides presentation. Advantages of jQuery over JavaScript are: Much easier to use.
Eliminates cross browser problems What is DOM ?DOM is a standardized object model across different browsers. The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM such as “Elements”  may be addressed and manipulated within the syntax of the programming language in use.
What is DOM ?There are four levels of standardized Document Object Model (DOM):Level 0Level 1Level 2Level 3 The DOM Level 2 combines both DOM Level 1 and 2. It provides methods to access and manipulate style sheet elements, and provides further access to page elements relating to XML. This Level 2 have six different recommendations: DOM2 CoreDOM2 HTMLDOM2 Style/CSSDOM2 EventsDOM2 Traversal and RangeDOM2 Views
What is jQuery ?jQuery is not a language, it is a well written Java Script code. Fast and Concise. Simplifies the interaction between HTML and Java Script. It’s syntax is same as JavaScript Syntax. jQuery helps, Improve the performance of the application. Develop most browser compatible web page. Implement UI related critical functionality. FastExtensibleMicrosoft is shipping jQuery with Visual Studio. jQuery supports intellisense in Visual Studio 2010 and with 2008 SP1. You can download latest version (1.6.1) of jQuery library at			http://docs.jquery.com/Downloading_jQuery
Why jQuery ?Lightweight : 31KB in size as per v1.6.1 (Minified and Gzipped)CSS 1–3 Complaint Cross Browser support	(IE 6.0, Fire Fox 2, Safari 3.0+, Opera 9.0, Chrome)jQuery allows you to elegantly (and efficiently) find and manipulate the HTML elements with minimum code. jQuery commands can be chained together. jQuery is “DOM Scripting”Great CommunityPluginsTutorialsTestCoverageOpen (free) licenseBooks
Who’s using jQuery?
jQuery Dominating Google trends comparison of JS Framework in last 12 months.
How to Embed jQuery in your PageBy assigning your jQuery script file to the “src” property of script tag. <html> 	<head> 		<script src=“path/to/jquery-x.x.js"></script> 		<script> 			$(document).ready(function(){				// Start here			}); 		</script> 	</head> 	<body> … </body> 	</html> To link jQuery remotely instead of hosting in your server:	<script type="text/javascript“ src="http://ajax.googleapis.com/ajax/libs/   jquery/1.4.0/jquery.min.js?ver=1.4.0"></script>jQuery Code
What jQuery ProvidesSelect DOM elements on a page. Either one element or group of them.Set properties of DOM elements, in groups. Creates, deletes, shows and hides DOM elements.Defines event behavior on a page Click, Mouse movement, Dynamic styles. Dynamic Content, Etc.,AnimationsAJAX calls.
jQuery Basics
jQuery PhilosophyThe below is the illustration of how jQuery works:{Find Some Elements$(“div”).addClass(“xyz”);}Do something with themjQuery Object
Basic ExampleThe following is a simple basic jQuery example how it works: Let us assume we have the following HTML and wants to select all paragraphs:<body> 		<div>		     <p>I m a paragraph 1</p> 		     <p>I m a paragraph 2</p> 	</div>	      <p>I m another paragraph</p> </body> To select all paragraphs, you can use following jQuery : $(“p”)
Add a class to all the paragraphs : $(“p”).addClass(“redStyle”);The jQuery FunctionjQuery() = $()$(function)     	The “Ready” handler$(‘selector’)	Element selector Expression$(element)		Specify element(s) directly$(‘HTML’)		HTML creation$.function()	Execute a jQuery function$.fn.myfunc() { } 	Create jQuery function
The Ready FunctionWith the help of jQuery ready() function, you can detect the state of readiness of your document to execute java script.The code included inside $(document).ready() will only run once the page is ready for JavaScript code to execute. $(document).ready(function() {	    		console.log('ready!');			});Inside the ready function the script will be executed when DOM is ready.You can also pass named function instead of anonymous function. 5 different ways to specify the ready functionjquery(document).ready(function(){…..};);jquery().ready(function(){….};)jquery(function(){ ….};)jquery(dofunc);$(dofunc);
jQuery Core
jQuery SelectorsjQuery offers a set of tools for matching set of elements in a document.If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:; <=>? @[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\.Ex: If you have an element with id="foo.bar", you can use selector $("#foo\\.bar").Some of the selector examples:  $(“*”); 	        	//Selects all elements.
$(“#elmtID”); 	//Selecting elements by ID. ID must be unique.
$(“div.myClass”); 	//Selecting elements by class name.
$(‘input[name=myName]’); 	//Selecting elements by attribute.
$(‘input[name$=myName]’); 	//Selecting elements it attribute ends with myName. Choosing the good selector can improve the performance of your selector. To test whether the specified selection contain elements or not. if ($('div.foo').length) { ... }  //If no elements it returns 0 and evaluates false.
jQuery SelectorsThe jQuery library allows you to select elements in your XHTML by wrapping them in $(“ ”). This $ sign in a jQuery wrapper. You can also use single quote to wrap the element.$("div"); 		// selects all HTML div elements
$("#myElmtD"); // selects one HTML element with ID "myElement"
$(".myClass"); 	// selects HTML elements with class "myClass"
$("p#myElmtID"); 	// selects HTML paragraph element with ID "myElement"
$("ullia.navigation"); // selects anchors with class "navigation" that are nested in list items. jQuery also support the use of CSS selectors also. 	$("p > a"); // selects anchors that are direct children of paragraphs
$("input[type=text]"); // selects inputs that have specified type
$("a:first"); // selects the first anchor on the page
$("p:odd"); // selects all odd numbered paragraphs
$("li:first-child"); // selects each list item that's the first child in its listjQuery SelectorsjQuery also allows the use of its own custom selectors: $(":animated"); 	// Selects elements currently being animated
$(":button"); 	// Selects any button elements (inputs or buttons)
$(":radio"); 	// Selects radio buttons
$(":checkbox"); 	// Selects checkboxes
$(":checked"); 	// Selects checkboxes or radio buttons that are selected
$(":header"); 	// Selects header elements (h1, h2, h3, etc.)
$(":disabled"); 	// Selects disabled form elements. (Enabled also there)
$(":img"); 		// Select inputs with type=“image”.
$(":file"); 		// Select inputs with type=“file”.
$(":password");		// Select inputs with type=“password”.Selecting Elements ExampleThe below are some of selectors examples:$(selector)   	//The below are examples of selectors.
$(‘#id’)		id of element.
$(‘p’)		tag name.
$(‘.class’)		CSS class
$(‘p.class’)		<p> elements having the CSS class
$(‘p:first’)	$(‘p:last’)	$(‘p:odd’) $(‘p:even’)
$(‘p:eq(2)’)		gets the 2nd <p> element (1 based)
$(‘p’)[1]		gets the 2nd <p> element (0 based)
$(‘p:nth-child(3))	gets the 3rd <p> element of the parent. n=even, odd too.
$(‘p:nth-child(5n+1)’)	gets the 1st element after every 5th one
$(‘p a’)		<a> elements, descended from a <p>
$(‘p>a’)		<a> elements, direct child of a <p>
$(‘p+a’)		<a> elements, directly following a <p>
$(‘p, a’)		<p> and <a> elements
$(‘li:has(ul)’)	<li> elements that have at least one <ul> descendent
$(‘:not(p)’)		all elements but <p> elements
$(‘p:hidden’)	only <p> elements that are hidden
$(‘p:empty’)	<p> elements that have no child elements
$(‘img’[alt])	<img> elements having an alt attributeSelecting Elements Example cont..,The below are some more selectors examples:$(‘a’[href^=http://]) 	//Select <a> elmt with an href attribute starting with ‘http://’.
$(‘a’[href$=pdf])	//Select <a> elmt with an href attribute ending with pdf
$(‘a’[href*=ntpcug])	//Select <a> elmt with an href attribute containing ‘ntpcug”. Working with Attributes The $fn.attr method acts as both a getter and setter. The $.fn.attr as a setter can accept either a key and a value, or an object containing one or more key/value pairs.$('a').attr('href', 'allMyHrefsAreTheSameNow.html');  //single attribute.$('a').attr({ 				// Multiple attribues. 'title' : 'all titles are the same too!', 'href' : 'somethingNew.html' });The below example demonstrates the getting attribute href of the first <a> element in the document. $('a').attr('href');
jQuery Core MethodsMost of the jQuery methods are called on jQuery objects. These are said to be part of the $.fn namespace and are called as jQuery object methods. There are several other methods that do not act on a selection, these are part of jQuery (i.e., $) namespace and are best thought of as core jQuery methods.  Methods in the $ namespace (or jQuery namespace) are called as utility methods and do not work with selections. Some of the utility methods are:$.trim();
$.each()
$.proxy()	    //Returns a function that will always run in the provided scope.
$.inArray()	    //Return a value’s index in an Array.
$.extend()	     //Change the properties of the first object using properties 			     // of subsequent objects. There are few cases the $.fn namespace and jQuery core name space methods have same name. (Eg: $.each and $.fn.each).
Traversing Elements Once you have a jQuery selection, you can find other elements using your selection as a starting point.With the help of jQuery traversal methods you can move around DOM tree. The below are the few traversal methods defined in jQuery: $('h1').next('p');
$('div:visible').parent();
Ad

More Related Content

What's hot (20)

JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
HTML
HTMLHTML
HTML
chinesebilli
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Jquery
JqueryJquery
Jquery
Girish Srivastava
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
XSLT.ppt
XSLT.pptXSLT.ppt
XSLT.ppt
KGSCSEPSGCT
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
Sun Technlogies
 
Html forms
Html formsHtml forms
Html forms
M Vishnuvardhan Reddy
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
IT Geeks
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
AbhishekMondal42
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
Html5 and-css3-overview
Html5 and-css3-overviewHtml5 and-css3-overview
Html5 and-css3-overview
Jacob Nelson
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
Java script
Java scriptJava script
Java script
Abhishek Kesharwani
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
Sun Technlogies
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
IT Geeks
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
AbhishekMondal42
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
Html5 and-css3-overview
Html5 and-css3-overviewHtml5 and-css3-overview
Html5 and-css3-overview
Jacob Nelson
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 

Viewers also liked (12)

Plm Open Hours - Ersatzteilkataloge und Produktdokumentation
Plm Open Hours - Ersatzteilkataloge und ProduktdokumentationPlm Open Hours - Ersatzteilkataloge und Produktdokumentation
Plm Open Hours - Ersatzteilkataloge und Produktdokumentation
Intelliact AG
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
Shivanand Arur
 
Introducing LINQ
Introducing LINQIntroducing LINQ
Introducing LINQ
LearnNowOnline
 
Linq
LinqLinq
Linq
Vishwa Mohan
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
Anand Kumar Rajana
 
Linq
LinqLinq
Linq
Inspirate Unaula
 
LINQ and LINQPad
LINQ and LINQPadLINQ and LINQPad
LINQ and LINQPad
Andreas Gullberg Larsen
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
Basant Medhat
 
Linq
LinqLinq
Linq
samneang
 
OPC Unified Architecture
OPC Unified ArchitectureOPC Unified Architecture
OPC Unified Architecture
Vishwa Mohan
 
Introduccion a LINQ
Introduccion a LINQIntroduccion a LINQ
Introduccion a LINQ
Tonymx
 
The ROI of Trust in Social Selling
The ROI of Trust in Social SellingThe ROI of Trust in Social Selling
The ROI of Trust in Social Selling
Barbara Giamanco
 
Ad

Similar to jQuery (20)

JQuery
JQueryJQuery
JQuery
Jacob Nelson
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
Jquery PPT_Finalfgfgdfgdr5tryeujkhdwappt
Jquery PPT_Finalfgfgdfgdr5tryeujkhdwapptJquery PPT_Finalfgfgdfgdr5tryeujkhdwappt
Jquery PPT_Finalfgfgdfgdr5tryeujkhdwappt
shubhangimalas1
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
Muhammad Afzal Qureshi
 
J Query(04 12 2008) Foiaz
J Query(04 12 2008) FoiazJ Query(04 12 2008) Foiaz
J Query(04 12 2008) Foiaz
testingphase
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb
 
J query
J queryJ query
J query
Ramakrishna kapa
 
J Query
J QueryJ Query
J Query
ravinxg
 
JQuery_and_Ajax.pptx
JQuery_and_Ajax.pptxJQuery_and_Ajax.pptx
JQuery_and_Ajax.pptx
AditiPawale1
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Doncho Minkov
 
Intro to jQuery
Intro to jQueryIntro to jQuery
Intro to jQuery
Alan Hecht
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
Isfand yar Khan
 
Jquery Basics
Jquery BasicsJquery Basics
Jquery Basics
Umeshwaran V
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks Trivia
Cognizant
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Gunjan Kumar
 
J Query Public
J Query PublicJ Query Public
J Query Public
pradeepsilamkoti
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
Salvatore Fazio
 
lec 14-15 Jquery_All About J-query_.pptx
lec 14-15 Jquery_All About J-query_.pptxlec 14-15 Jquery_All About J-query_.pptx
lec 14-15 Jquery_All About J-query_.pptx
MuhammadAbubakar114879
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
J query training
J query trainingJ query training
J query training
FIS - Fidelity Information Services
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
Jquery PPT_Finalfgfgdfgdr5tryeujkhdwappt
Jquery PPT_Finalfgfgdfgdr5tryeujkhdwapptJquery PPT_Finalfgfgdfgdr5tryeujkhdwappt
Jquery PPT_Finalfgfgdfgdr5tryeujkhdwappt
shubhangimalas1
 
J Query(04 12 2008) Foiaz
J Query(04 12 2008) FoiazJ Query(04 12 2008) Foiaz
J Query(04 12 2008) Foiaz
testingphase
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb
 
JQuery_and_Ajax.pptx
JQuery_and_Ajax.pptxJQuery_and_Ajax.pptx
JQuery_and_Ajax.pptx
AditiPawale1
 
Intro to jQuery
Intro to jQueryIntro to jQuery
Intro to jQuery
Alan Hecht
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
Isfand yar Khan
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks Trivia
Cognizant
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Gunjan Kumar
 
lec 14-15 Jquery_All About J-query_.pptx
lec 14-15 Jquery_All About J-query_.pptxlec 14-15 Jquery_All About J-query_.pptx
lec 14-15 Jquery_All About J-query_.pptx
MuhammadAbubakar114879
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
Ad

More from Vishwa Mohan (13)

WPF
WPFWPF
WPF
Vishwa Mohan
 
Wwf
WwfWwf
Wwf
Vishwa Mohan
 
Da package usersguide
Da package usersguideDa package usersguide
Da package usersguide
Vishwa Mohan
 
Dareadme
DareadmeDareadme
Dareadme
Vishwa Mohan
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
Uml
UmlUml
Uml
Vishwa Mohan
 
Xml
XmlXml
Xml
Vishwa Mohan
 
Real Time Systems &amp; RTOS
Real Time Systems &amp; RTOSReal Time Systems &amp; RTOS
Real Time Systems &amp; RTOS
Vishwa Mohan
 
Embedded Linux
Embedded LinuxEmbedded Linux
Embedded Linux
Vishwa Mohan
 
Introduction To Embedded Systems
Introduction To Embedded SystemsIntroduction To Embedded Systems
Introduction To Embedded Systems
Vishwa Mohan
 
Microsoft.Net
Microsoft.NetMicrosoft.Net
Microsoft.Net
Vishwa Mohan
 
Zig Bee
Zig BeeZig Bee
Zig Bee
Vishwa Mohan
 
WCF
WCFWCF
WCF
Vishwa Mohan
 

Recently uploaded (20)

How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 

jQuery

  • 1. jQueryWrites less, Do MoreCh. Vishwa MohanFreelance Software Consultant &Corporate Trainer
  • 2. Table of ContentsjQuery IntroductionjQuery BasicsjQuery CoreEventsAnimationAJAXPlugins
  • 5. With AJAX . . .JavaScript has become essential to current web page development, but.. JavaScript is not a good language design.JavaScript has become bloatedDOM Navigation
  • 6. Browser differencesWriting JavaScript code is tedious, time-consuming and error prone.
  • 7. Why you might want to use jQueryjQuery makes writing Javascript much easier. DOM Navigation (CSS-like syntax)
  • 8. Apply methods to sets of DOM elements.
  • 9. Builder model (chain method calls)
  • 10. Extensible and there are tons of libraries
  • 11. Handles most of browser differences so you don’t have to Server provides datajQuery on client provides presentation. Advantages of jQuery over JavaScript are: Much easier to use.
  • 12. Eliminates cross browser problems What is DOM ?DOM is a standardized object model across different browsers. The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM such as “Elements” may be addressed and manipulated within the syntax of the programming language in use.
  • 13. What is DOM ?There are four levels of standardized Document Object Model (DOM):Level 0Level 1Level 2Level 3 The DOM Level 2 combines both DOM Level 1 and 2. It provides methods to access and manipulate style sheet elements, and provides further access to page elements relating to XML. This Level 2 have six different recommendations: DOM2 CoreDOM2 HTMLDOM2 Style/CSSDOM2 EventsDOM2 Traversal and RangeDOM2 Views
  • 14. What is jQuery ?jQuery is not a language, it is a well written Java Script code. Fast and Concise. Simplifies the interaction between HTML and Java Script. It’s syntax is same as JavaScript Syntax. jQuery helps, Improve the performance of the application. Develop most browser compatible web page. Implement UI related critical functionality. FastExtensibleMicrosoft is shipping jQuery with Visual Studio. jQuery supports intellisense in Visual Studio 2010 and with 2008 SP1. You can download latest version (1.6.1) of jQuery library at http://docs.jquery.com/Downloading_jQuery
  • 15. Why jQuery ?Lightweight : 31KB in size as per v1.6.1 (Minified and Gzipped)CSS 1–3 Complaint Cross Browser support (IE 6.0, Fire Fox 2, Safari 3.0+, Opera 9.0, Chrome)jQuery allows you to elegantly (and efficiently) find and manipulate the HTML elements with minimum code. jQuery commands can be chained together. jQuery is “DOM Scripting”Great CommunityPluginsTutorialsTestCoverageOpen (free) licenseBooks
  • 17. jQuery Dominating Google trends comparison of JS Framework in last 12 months.
  • 18. How to Embed jQuery in your PageBy assigning your jQuery script file to the “src” property of script tag. <html> <head> <script src=“path/to/jquery-x.x.js"></script> <script> $(document).ready(function(){ // Start here }); </script> </head> <body> … </body> </html> To link jQuery remotely instead of hosting in your server: <script type="text/javascript“ src="http://ajax.googleapis.com/ajax/libs/ jquery/1.4.0/jquery.min.js?ver=1.4.0"></script>jQuery Code
  • 19. What jQuery ProvidesSelect DOM elements on a page. Either one element or group of them.Set properties of DOM elements, in groups. Creates, deletes, shows and hides DOM elements.Defines event behavior on a page Click, Mouse movement, Dynamic styles. Dynamic Content, Etc.,AnimationsAJAX calls.
  • 21. jQuery PhilosophyThe below is the illustration of how jQuery works:{Find Some Elements$(“div”).addClass(“xyz”);}Do something with themjQuery Object
  • 22. Basic ExampleThe following is a simple basic jQuery example how it works: Let us assume we have the following HTML and wants to select all paragraphs:<body> <div> <p>I m a paragraph 1</p> <p>I m a paragraph 2</p> </div> <p>I m another paragraph</p> </body> To select all paragraphs, you can use following jQuery : $(“p”)
  • 23. Add a class to all the paragraphs : $(“p”).addClass(“redStyle”);The jQuery FunctionjQuery() = $()$(function) The “Ready” handler$(‘selector’) Element selector Expression$(element) Specify element(s) directly$(‘HTML’) HTML creation$.function() Execute a jQuery function$.fn.myfunc() { } Create jQuery function
  • 24. The Ready FunctionWith the help of jQuery ready() function, you can detect the state of readiness of your document to execute java script.The code included inside $(document).ready() will only run once the page is ready for JavaScript code to execute. $(document).ready(function() { console.log('ready!'); });Inside the ready function the script will be executed when DOM is ready.You can also pass named function instead of anonymous function. 5 different ways to specify the ready functionjquery(document).ready(function(){…..};);jquery().ready(function(){….};)jquery(function(){ ….};)jquery(dofunc);$(dofunc);
  • 26. jQuery SelectorsjQuery offers a set of tools for matching set of elements in a document.If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:; <=>? @[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\.Ex: If you have an element with id="foo.bar", you can use selector $("#foo\\.bar").Some of the selector examples: $(“*”); //Selects all elements.
  • 27. $(“#elmtID”); //Selecting elements by ID. ID must be unique.
  • 30. $(‘input[name$=myName]’); //Selecting elements it attribute ends with myName. Choosing the good selector can improve the performance of your selector. To test whether the specified selection contain elements or not. if ($('div.foo').length) { ... } //If no elements it returns 0 and evaluates false.
  • 31. jQuery SelectorsThe jQuery library allows you to select elements in your XHTML by wrapping them in $(“ ”). This $ sign in a jQuery wrapper. You can also use single quote to wrap the element.$("div"); // selects all HTML div elements
  • 32. $("#myElmtD"); // selects one HTML element with ID "myElement"
  • 33. $(".myClass"); // selects HTML elements with class "myClass"
  • 34. $("p#myElmtID"); // selects HTML paragraph element with ID "myElement"
  • 35. $("ullia.navigation"); // selects anchors with class "navigation" that are nested in list items. jQuery also support the use of CSS selectors also. $("p > a"); // selects anchors that are direct children of paragraphs
  • 36. $("input[type=text]"); // selects inputs that have specified type
  • 37. $("a:first"); // selects the first anchor on the page
  • 38. $("p:odd"); // selects all odd numbered paragraphs
  • 39. $("li:first-child"); // selects each list item that's the first child in its listjQuery SelectorsjQuery also allows the use of its own custom selectors: $(":animated"); // Selects elements currently being animated
  • 40. $(":button"); // Selects any button elements (inputs or buttons)
  • 41. $(":radio"); // Selects radio buttons
  • 43. $(":checked"); // Selects checkboxes or radio buttons that are selected
  • 44. $(":header"); // Selects header elements (h1, h2, h3, etc.)
  • 45. $(":disabled"); // Selects disabled form elements. (Enabled also there)
  • 46. $(":img"); // Select inputs with type=“image”.
  • 47. $(":file"); // Select inputs with type=“file”.
  • 48. $(":password"); // Select inputs with type=“password”.Selecting Elements ExampleThe below are some of selectors examples:$(selector) //The below are examples of selectors.
  • 54. $(‘p:eq(2)’) gets the 2nd <p> element (1 based)
  • 55. $(‘p’)[1] gets the 2nd <p> element (0 based)
  • 56. $(‘p:nth-child(3)) gets the 3rd <p> element of the parent. n=even, odd too.
  • 57. $(‘p:nth-child(5n+1)’) gets the 1st element after every 5th one
  • 58. $(‘p a’) <a> elements, descended from a <p>
  • 61. $(‘p, a’) <p> and <a> elements
  • 62. $(‘li:has(ul)’) <li> elements that have at least one <ul> descendent
  • 65. $(‘p:empty’) <p> elements that have no child elements
  • 66. $(‘img’[alt]) <img> elements having an alt attributeSelecting Elements Example cont..,The below are some more selectors examples:$(‘a’[href^=http://]) //Select <a> elmt with an href attribute starting with ‘http://’.
  • 67. $(‘a’[href$=pdf]) //Select <a> elmt with an href attribute ending with pdf
  • 68. $(‘a’[href*=ntpcug]) //Select <a> elmt with an href attribute containing ‘ntpcug”. Working with Attributes The $fn.attr method acts as both a getter and setter. The $.fn.attr as a setter can accept either a key and a value, or an object containing one or more key/value pairs.$('a').attr('href', 'allMyHrefsAreTheSameNow.html'); //single attribute.$('a').attr({ // Multiple attribues. 'title' : 'all titles are the same too!', 'href' : 'somethingNew.html' });The below example demonstrates the getting attribute href of the first <a> element in the document. $('a').attr('href');
  • 69. jQuery Core MethodsMost of the jQuery methods are called on jQuery objects. These are said to be part of the $.fn namespace and are called as jQuery object methods. There are several other methods that do not act on a selection, these are part of jQuery (i.e., $) namespace and are best thought of as core jQuery methods. Methods in the $ namespace (or jQuery namespace) are called as utility methods and do not work with selections. Some of the utility methods are:$.trim();
  • 71. $.proxy() //Returns a function that will always run in the provided scope.
  • 72. $.inArray() //Return a value’s index in an Array.
  • 73. $.extend() //Change the properties of the first object using properties // of subsequent objects. There are few cases the $.fn namespace and jQuery core name space methods have same name. (Eg: $.each and $.fn.each).
  • 74. Traversing Elements Once you have a jQuery selection, you can find other elements using your selection as a starting point.With the help of jQuery traversal methods you can move around DOM tree. The below are the few traversal methods defined in jQuery: $('h1').next('p');
  • 78. $('li.selected').siblings();You can also iterate over a selection using $fn.each() function. This function iterates over all elements in a selection. The function receives the index of the current element and the DOM element itself as argumentsInside the function, the DOM element is available as this by default. $('#myListli').each(function(idx, el) { console.log('Element ' + idx + 'has the following html: ' + $(el).html() ); });
  • 79. Storing SelectionsIf you made a selection, that might need to make again you should save the selection in a variable rather then making it again (It improves performance).var$allDivs = $('div'); Here variable name begin with $ sign.
  • 80. Here $ is another character there is no special meaning for it.
  • 81. It is a convention and not mandatory.
  • 82. Once you stored in variable you can call jQuery method on it.
  • 83. Stored selections doesn’t update when the DOM changes. You can call methods on the selection. Methods have two different flavors getters and setters. Normally getter and setter methods will have same name. $('h1').html(); //Getter return the html for first h1. $('h1').html('hello world'); //The $.fn.html() method used as a setter.Getters get the requested value only for the first element in the selection.
  • 84. Setters affects all elements in a selection.
  • 85. Setters return a jQuery object, allowing you to continue to call jQuery methods on your selection; getters return whatever they were asked to get. Useful jQuery FunctionsThe below are the some of the useful jQuery functions: .each() iterate over the set
  • 87. .end() reverts to the previous set
  • 88. .get(n) get just the nth element (0 based)
  • 89. .eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)
  • 90. .slice(n,m) gets only nth to (m-1)th elements
  • 93. .remove() removes all the elements from the page DOM
  • 94. .empty() removes the contents of all the elements
  • 95. .filter(fn/sel) selects elements where the func returns true or sel
  • 97. .parent() returns the parent of each element in set
  • 98. .children() returns all the children of each element in set
  • 99. .next() gets next element of each element in set
  • 100. .prev() gets previous element of each element in set
  • 101. .siblings() gets all the siblings of the current elementAccessing & Manipulating CSS Class NamesjQuery allows you to easily add, remove, and toggle CSS classes. $("div").addClass("content"); // adds class "content" to all <div> elements
  • 102. $("div").removeClass("content"); // removes class "content" from all <div> elmts
  • 103. $("div").toggleClass("content"); //toggle the class “content”You can also check to see if any of the selected element has particular class$("#myElement").hasClass("content")The above jQuery function hasClass also use to check a set of elements (instead of just one), and the result would be “true” if any of the element containing the class.
  • 104. Manipulating CSS StylesjQuery includes a handy way to get and set CSS properties of elements.CSS properties that normally include a hyphen need to be camel cased in JavaScript. (Eg: CSS property font-size is expressed as fontSize in JavaScript).$('h1').css('fontSize'); // returns a string such as “20px"With jQuery, CSS style can be added: $("p").css("width", "400px"); // adds a width to all paragraphs
  • 105. $("#myElemt").css("color", "blue") // makes text color blue on element #myElemt
  • 106. $("ul").css("border", "solid 1px #ccc") // adds a border to all lists
  • 107. $(“h1").css(‘fontSize’, ‘100px’); // Setting an individual property.
  • 108. $(“h1").css(‘fontSize’, ‘100px’, ‘color” : ‘red”); // Setting multiple properties. Instead of changing CSS styles via hardcode you can apply CSS class on elements. It is a better approach (No hard code). var$h1 = $('h1'); $h1.addClass(‘myClass'); //removeClass and toggleClass is also there.You can also find any particular CSS class applied for a given element: if ($h1.hasClass('myClass')) { ... }
  • 109. Adding, Removing & Appending Elements and ContentsjQuery, easily manipulates the group of elements including their contentsGet the HTML of any element (similar to innerHTML in JavaScript). The below code returns all HTML(including text) inside #myElement. varmyElementHTML = $("#myElement").html();For the above you don’t’ want to access the HTML, but only want the text of an element, then use text() instead of html().varmyElementHTML = $("#myElement").text(); //Excludes HTML markup. If you want to change the HTML or text content of specified element:$("#myElement").html("<p>This is the new content.</p>"); //Content is replaced. $("#myElement").text(“This is the new content. "); //Only text content is replaced. To append content to element. (Add the content to end of existing) $("#myElement").append("<p>This is the new content.</p>"); $(“p").append("<p>This is the new content.</p>"); //Add to end of all paragraphs jQuery also offers the use of the following commands: appendTo(), prepend(), before(), insertBefore(), after(), wrap() andinsertAfter(). $(‘#target’).before(‘<p>Inserted before #target</p>’); $(‘#target’).wrap(‘<div></div>’);
  • 110. Manipulating ElementsOnce you’ve made a selection on the elements, you can change, move, remove and clone the elements. Basically changing the element means manipulating DOM in some manner. But most commonly you can change inner HTML or attribute of an element.
  • 111. When method acts as getters, generally only works with the first element in the selection, and they don’t return jQuery object, so you don’t chain additional methods to them. One notable exception is $fn.text;Some of the manipulating functions are:$fn.html(); //Get or set the HTML contents. Eg : $('#myDiv p:first').html('New <strong>first</strong> paragraph!');$fn.text(); //Get or set the text contents. HTML will be stripped.
  • 112. $fn.attr(); //Get or set the value of the provided attribute.
  • 113. $fn.val(); //Gets or sets the value of an form element.
  • 114. $fn.width(); //Gets or sets the width in pixels of the first element in the // selection as an integer. Height is also there.
  • 115. $fn.position(); //Only getter. Gets the position information. Moving, Copying ElementsThere are many ways to move elements around the DOM. The below are some of the methods. $fn.insertAfter(); //Places the selected element(s) after the element you //provided as argument.
  • 116. $fn.after(); //Places the element provided as an argument after the //selected element.
  • 122. $fn.prepend(); The below is a simple jQuery code make the first list item the last list item. var $li = $('#myListli:first').appendTo('#myList');
  • 123. Removing ElementsThere are two ways to remove elements from the page. They are $.fn.removeand $.fn.detach. The remove function will remove the selections from the page; while the method does returns the removed element(s). The detach function will persist the data and events. There is a one more function empty, it simply remove its contents but leaves the elements on the page.
  • 124. Creating new ElementsjQuery offers a trivial and elegant way to create new elements using the same $() method you use to make selections. Eg:$('<p>This is a new paragraph</p>');$('<li class="new">new list item</li>');Creating a new element with an attribute object. $('<a/>', {html : 'This is a <strong>new</strong> link','class' : 'new',href : 'foo.html‘ });Able the attributes object we included as the second argument,
  • 125. The property name class is quoted, while the property names text and href are not. Because property is quoted it is reserved word.(as class is in this case).Showing & Hiding ElementsThe syntax for showing, hiding and toggling elements is given below: $("#myElement").hide("slow", function() { // This code is executed once the element is hidden. }$("#myElement").show(“fast", function() { // This code is executed once the element is shown. }$("#myElement").toggle(1000, function() { // This code is executed once the element is shown or hidden. } You can also make fade and element in or out. $("#myElement").fadeOut("slow", function() { //Similarly fadeIn is there., }); // This function called when fadeOut is finished. To fade an element only partially either in or out. $("#myElement").fadeTo(2000, 0.4, function() { }); // called when fade is finished.The second parameter 0.4 is opacity. Similar to way opacity set in CSS. Animations and EffectsWith the help of jQuery you can slide elements, animate elements and even stop animation in mid-sequence. $("#myElement"). slideDown(“fast", function() { // This code is executed when the slide down is finished. }Similarly you have slideUp, slideToggle functions defined. To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles but instead of setting instantly, it does so gradually, animating the effect at chosen speed. $("#myElement").animate( { opacity: .3, width: "500px", height: "700px"}, 2000, function() { // Optional callback calls after animation completes});
  • 126. Events in jQueryThe below code inside function() will be executed when an anchor is clicked.$("a").click(function() { // do something here when any anchor is clicked}); The following are some of the comment events you can use in jQuery:blur,
  • 127. focus,
  • 128. hover,
  • 130. load,
  • 135. select.ChainingOne of the jQuery feature is chaining. If you call a method on a selection and that method returns a jQuery object, you can continue to call jQuery methods on the object without pausing for semicolon. (Powerful technique).$('#content').find('h3').eq(2).html('new text for the third h3!');Formatting the above chain code looks like below: (Good readability)$('#content') .find('h3') .eq(2) .html('new text for the third h3!');If you change your selection in the midst of a chain, jQuery provides the $.fn.endmethod to get you back to your original selection.$('#content').find('h3').eq(2) .html('new text for the third h3!').end() // restores the selection to all h3's in #content .eq(0) .html('new text for the first h3!');
  • 136. Type CheckingThere are set of jQuery core methods define to check for non-primitive types.$.isFunction();$.isArray();$.isPlainObject();
  • 138. Events BackgroundDOM is the standardized object model across different browsers. DOM Level 2 Event ModelMultiple event handlers, or listeners can be established on an element.
  • 139. These event handlers, can’t be relied upon to run on any particular order.
  • 140. When triggered, the event propagates from the top down(capture phase) or bottom up (bubble phase).
  • 141. IE doesn’t support “capture phase”. jQuery provides simple methods for attaching event handlers to selections. When an event occurs, the provided function is executed. Inside the function, this refers to element that was clicked.
  • 142. The event handling function can receive an event object. This object can be used to determine the nature of the event, and to prevent the event’s default behavior. Basic Syntax of Event BindingFollowing is the syntax of event binding mechanism using $.fn.bind method: Eg: $(‘img’).bind(‘click’, function(event) { alert(‘Howdy’; });$('p').bind('click', function() { alert('click'); } );$(‘img’).bind(‘click’, imgclick(event));  $(‘img’).click(imgClick); Event binding with data using $.fn.bind method$('input').bind( 'clickchange', // bind to multiple events { foo : 'bar' }, // pass in data function(eventObject) { console.log(eventObject.type, eventObject.data); });To disconnect an event handler, you can use the $.fn.unbind() method and pass in the event type to unbind. $(‘p’).unbind(‘click’); //unbinding all click handlers. $('p').bind('click', fooFunc).bind('click', barFunc); //Click binded with two funcs.$('p').unbind('click', barFunc); //Unbinded only barFunc still fooFunc still binded.If you attached a named function to the event, then you can isolate the unbinding to that named function by passing it as the second argument.$(‘img’).unbind(‘click’, imgclick()); //Unbinding named function. Connecting Events to Run Only OnceIf you need a particular handler to run only once -- after that, you may want no handler to run, or you may want a different handler to run. jQuery provides the $.fn.onemethod for this purpose.$('p').one('click', function() { console.log('You just clicked this for the first time!');$(this).click(function() { console.log('You have clicked this before!'); });Some of the other event bindings examples are:$(‘img’).one(imgclick);
  • 144. $(‘img’).hover(mouseover, mouseout);Event BindingsSome of the other event bindings examples are:$(‘img’).one(imgclick);
  • 146. $(‘img’).hover(mouseover, mouseout);Sometimes it can be useful to namespaces your events so you don’t unintentionally disconnect events that you don’t know about it. (Specially using in plug-ins).$('p').bind('click.myNamespace', function() { /* ... */ });$('p').unbind('click.myNamespace');$('p').unbind('.myNamespace'); // unbind all events in the namespace
  • 147. Convince Method Event BindingjQuery offers convenience methods for most common events, these methods are used very frequently. These methods are: $.fn.click, $.fn.focus, $.fn.blur, $.fn.change,etc.., $('p').click(function() { console.log('click'); });The above methods are shorthand for jQuery’s$fn.bindmethod.
  • 148. This bind method is useful for binding the same handler function to multiple events, and is also used when you want to provide data to the event hander, or when you are working with custom events.The following are examples of event binding using convince method: .click(func)
  • 153. .select(func)Inside Event Handling FunctionThe event handling function receives an event object, which contains many properties and methods. The event object is commonly used to prevent the default action of the event via the preventDefault method.
  • 154. In addition to event object the event handler also has access to DOM element that that handler was bound via the key word ‘this’. To turn the DOM element into jQuery object by simply doing $(this).var $this = $(this);Eg: $('a').click(function(e) {var $this = $(this); if ($this.attr('href').match('evil')) {e.preventDefault();$this.addClass('evil'); } });
  • 155. Event PropertiesThe event object contains a number of useful properties and methods: pageX, pageY //The mouse position at the time of event occur.
  • 156. type //The type of event eg: “click”
  • 157. which //The button or the key that was pressed.
  • 158. data //Any data that was passed as second param of bind func.
  • 159. target // The DOM element that initiated the event. Triggering elmt
  • 160. target.id // Event triggering element ID.
  • 162. preventDefault() //Prevents the default action of event. Eg: following a link.
  • 163. stopPropagation() //Stop the event from bubbling up to other elements. In addition to above properties you can find various mouse coordinate and key stroke related properties.
  • 164. Element Properties via “this”You can retrieve the element properties with “this”this
  • 172. this.value (for form elements)Event MethodsThe following are the some of the event methods: .stopPropagation() no bubbling
  • 173. .preventDefault() no <a> link, no <form> submit
  • 174. .trigger(eventType) does not actually trigger the event, but calls the appropriate function specified as the one tied to the eventType
  • 175. .click(), blur(), focus(), select(), submit()
  • 176. With no parameter, invokes the event handlers, like trigger does, for all the elements in the wrapped setThe below are some of the useful Event functions: .hide()display:none
  • 178. .toggle(func1, func2) first click calls func1, next click executes func2
  • 179. .hover(over, out)mouseover, mouseoutTriggering EventsjQuery provides a way to trigger the event handlers bound to an element without any user interaction via the $.fn.triggermethod. While this method has its uses, it should not be used simply to call a function that was bound as a click handler. Instead, you should store the function you want to call in a variable, and pass the variable name when you do your binding. Then, you can call the function itself whenever you want, without the need for $.fn.trigger.varfoo = function(e) { if (e) { console.log(e); } else { console.log('this didn\'t come from an event!') }}; $('p').click(foo); foo(); // instead of $('p').trigger('click')
  • 180. Event DelegationWith event delegation, you can increase the performance of your code. With event delegation, you bind your event to a container element, and then when the event occurs, you look to see which contained element it occurred on. To support above delegation jQuery provides $.fn.live and $.fn.delegatemethods.
  • 181. Event HelpersjQuery offers two event-related helper functions that save you a few keystrokes.$.fn.hover//Mouse hover over an element.
  • 182. $.fn.toggleThe $.fn.hoverfunction lets you pass one or two functions to be run when the mouseenter and mouseleave events occur on an element. If you pass one function it will be run for both events.
  • 183. If you pass two functions, the fist will run for mouse enter, and the second will run for mouse leave. The $.fn.toggle method receives two or more functions; each time the event occurs, the next function in the list is called. Generally, $.fn.toggle is used with just two functions, but technically you can use as many as you'd like.$('p.expander').toggle( function() { $(this).prev().addClass('open');}, function() { $(this).prev().removeClass('open'); } );
  • 185. EffectsjQuery makes it trivial to add simple effects to your page. Effects can use the built-in settings, or provide a customized duration. Frequently used effects are built into jQuery as methods. They are:$.fn.show//Show the selected element. (Eg: $(‘h1’).show();)$.fn.hide//Hide the selected elements.$.fn.fadeIn//Animate the opacity of the selected element to 100%. $.fn.fadeOut//Animate the opacity of the selected element to 0%. $.fn.slideDown//Display the selected elements with a vertical sliding motion. $.fn.slideUp//Hide the selected elements with a vertical sliding motion. $.fn.slideToggle//Show or hide the selected elements with a vertical sliding. Except $.fn.showand $.fn.hide, all of the built-in methods are animated over the course of 400ms by default. You can also change the duration of effect. $('h1').fadeIn(300); // fade in over 300ms$('h1').fadeOut('slow'); // using a built-in speed definitionjQuery has an object at jQuery.fx.speeds that contains the default speed, as well as settings for "slow" and "fast".You can also create custom animations of arbitrary CSS properties
  • 186. Animation in jQueryIf you want to run some code after the animation has done, then you can register a callback function for that particular animation. $('div.old').fadeOut(300, function() { $(this).remove(); }); jQuery makes it possible to animate any arbitrary CSS properties via the $fn.animate method. This method lets you animate to a set value or to a value relative to the current value. $('div.funtimes').animate( { left : "+=50", opacity : 0.25 }, //CSS properties 300, // duration function() { alert('done!'); // calback});Take note, color related properties can’t be animated with $fn.animate method. Color animations can be done by color plug-ins. jQuery provides several methods for managing animations: $.fn.stop//Stop currently running animation on the selected element.
  • 187. $.fn.delay//Waits for specified time before running next animation. $('h1').show(300).delay(1000).hide(300);
  • 188. Easing Easing describes the manner in which an effect occurs -- whether the rate of change is steady, or varies over the duration of the animation. jQuery includes only two methods of easing: swing and linear. In addition various easing plug-in’s are available. As of jQuery 1.4, it is possible to do per-property easing when using the $.fn.animate method.$('div.funtimes').animate( { left : ["+=50", "swing" ], opacity : [ 0.25, "linear" ] }, 300);
  • 189. AJAX
  • 190. Ajax OverviewIt is possible to trigger a AJAX request by Javascript code.Javascript code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response.
  • 191. The XMLHttpRequest method (XHR) allows browsers to communicate with the server without requiring a page reload.
  • 192. jQuery provides Ajax support that abstracts away painful browser differences.
  • 193. jQuery offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().
  • 194. Most of jQuery applications use XML and they transport data as plain HTML and JSON.
  • 195. In general, Ajax does not work across domains.
  • 196. Exceptions are services that provide JSONP (JSON with Padding) support, which allow limited cross-domain functionality.AJAX Key ConceptsThe two most common methods for sending request to a server are GET and POST. The GET method should be used for non-destructive operations. With GET request, you are only getting data from the server, not changing the data on the server. (Eg: Querying a search service).
  • 197. GET requests may be cached by the browser.
  • 198. GET request generally send all of their data in a query string. The POST method should be used for destructive operations (i.e., operation where you are changing data on the server). POST requests are generally not cached by the browser.
  • 199. A query string can be part of the URL, but the data tends to be separately as post data. Data TypesjQuery generally requires some instruction as to the type of data you expect to get back from an AJAX request. Some times the data type is specified by the method name, in some other cases it is provided as part of a configuration object. The different data types used in jQuery with AJAX requests are:text // To tranport simple strings.
  • 200. html // To transport blocks of HTML to be placed on the page.
  • 201. script // Adding new script to the page.
  • 202. json // To transport JSON-formatted data.
  • 203. jsonp // To transport JSON data from another domain.
  • 204. xml // to transport data in a custom XML schema. Same-Origin Policy and JSONPIn general, Ajax requests are limited to the same protocol (http or https), the same port, and the same domain as the page making the request. This limitation does not apply to scripts that are loaded via jQuery's Ajax methods.
  • 205. The other exception is requests targeted at a JSONP service on another domain. jQuery’s Ajax Related MethodsjQuery offers many Ajax related convenience methods, the heart of the all of the methods is $.ajax()The $.ajax() method is powerful and straight forward way of creating Ajax requests. It offers ability to specify both success and failure callbacks. Also the $.ajax() method has the ability to take a configuration object that can be defined separately makes it easier to write reusable code. The configuration object contains all the instructions requires for jQuery to complete the request. $.ajax({ url : ‘MyPage.php', data : { id : 123 }, //data converted into query string type: ‘GET’, //Request type either GET or POST  dataType : ‘json’ // The type of data we expect back. success: function(jsonRespObj) { …..}, //If request success, this code will run. error : function(xhr, staturs) {…}, //Code will run if request fails. complete: function(xhr, status) { ..} //Code will run for both success and failure. });
  • 206. $.ajax method OptionsThere are many, many options for the $.ajax method, some of them are:Async //Set false if you want to make synchronous request.
  • 207. Cache //Whether to use cached response if available. Default is true for all //data types except script and jsonp.
  • 208. Complete //Function to run after completion of request for (success or failure).
  • 209. Context //The scope which callback functions would run.
  • 210. Data //Data to be sent to server, it can be object or query string.
  • 211. dataType //Type of data expect from server. Not specified look for MIME type.
  • 212. Error //If request fails this callback function will be called.
  • 213. Jsonp // Callback name to send in a query string making a jsonp request.
  • 214. Success // If request success this function will be executed.
  • 215. Timeout //Time to wait in milliseconds before saying request is failed.
  • 216. Traditional //Specify to set serialization style.
  • 217. Type //Specify the request type GET, POST, PUT and DELETE.
  • 218. url //URL for the request. Convince MethodsAjax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests. These methods are just "wrappers" around the core $.ajax() method, and simply pre-set some of the options on the $.ajax() method.The convenience methods provided by jQuery are:$.get() //Performs the GET request to the provided URL.
  • 219. $.post() //Performs a POST request to the provided URL.
  • 220. $.getJSON() //Performs a GET request and expects JSON response. Eg: $.get('/users.php', { userId: 1234 }, function(resp) { console.log(resp); });All the above methods takes the following arguments in the given order:
  • 221. url//Required. The URL for the request.
  • 222. data //Optional. The data can be sent to server. It can be object //or query string (Eg: foo=bar&baz=bim)
  • 223. scucesscallback//Optional. A callback routine need to run on succes
  • 224. datatype//Optional. The data type that can expect from server. Convince MethodsThe $.fn.load() method is unique among jQuery’s Ajax methods in that it is called on a selection.$('#newContent').load('/foo.html');The $.fn.load method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s).
  • 225. In addition to providing a URL to the method, you can optionally provide a selector; jQuery will fetch only the matching content from the returned HTML.The following example is a jQuery way to run a script from a script file. $.getScript('/static/js/myScript.js', function() {functionFromMyScript(); });
  • 226. Ajax and FormsjQuery’s AJAX capabilities can be especially useful when dealing with forms. jQuery Form Plug-in is a tool for adding Ajax capabilities to forms. There are a two jQuery methods related to form processing are:$.fn.serialize()
  • 227. $.fn.serializeArray()Turning form data into query string:$('#myForm').serialize();Creating an array of objects containing form data $('#myForm'). serializeArray();
  • 228. Working with jsonpjQuery handles all the complex aspects of JSONP behind-the-scenes -- all we have to do is tell jQuery the name of the JSONP callback parameter specified by "callback“, and otherwise the whole process looks and feels like a normal Ajax request.
  • 229. AJAX EventsAjax also supports set of events such as ajax request start or stop events. These events are useful for showing or hiding a loading indicator. The following are the list of AJAX events:StartStopThe following is a Setting up loading indicator. It can be used for all Ajax events:$('#loading_indicator') .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); });
  • 231. jQueryPluginsThe point of a jQuery plug-in is to extend jQuery's prototype object.A jQuery plug-in is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add.
  • 232. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.The idea of a plug-in is to do something with a collection of elements. You could consider each method that comes with the jQuery core a plugin, like fadeOut or addClass.ReferencesjQuery Home page :http://jquery.comjQuery tutorial Blog:http://learningjquery.comhttp://visualjquery.comRick StrahI’s blog on jQuery : http://www.west-wind.com/weblog/Book : jQuery in Action :