SlideShare a Scribd company logo
Introduction toGunjan Kumar
AgendaWhat is jQueryGetting Startedthe famous $ signselectors  and managing wrapped setManipulating attributes, class, content for elementsDOM traversal and manipulationsome utility functionseffects provided by jQuery coreevents and getting close to unobtrusive JavaScripttemplateAjaxjQueryPluginjQuery UIjQuery Mobile
What is jQueryPer their website, “jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.”It was first released in Jan 2006, current release is 1.4.4Lightweight (24KB), CSS3 compliant, Cross BrowserA separate UI library and Mobile LibraryUsed by over 41% of the 10,000 most visited websites (majors like Google, Dell, Bank of America, NBC, Netflix … )Supported by Microsoft as well Per http://trends.builtwith.com/, jQuery and jQuery UI constitute around 50% of all JS libraries used on the web
Other JS librariesSWFObject is a small Javascript file used for embedding Adobe Flash content (http://code.google.com/p/swfobject/ )Prototype  : http://www.prototypejs.org/The Yahoo! User Interface (YUI) Library : http://developer.yahoo.com/yui/script.aculo.us : http://script.aculo.us/MooTools  : http://mootools.net/ Google Mashup Editor (GME)  : retired but still in use http://code.google.com/gme/
jQuery Resourceshttp://jquery.com/ : this is the core website.http://docs.jquery.com/Main_Page : developer’s starting pagehttp://docs.jquery.com/Tutorials : tutorialshttp://plugins.jquery.com/ : plugin repositoryhttp://jqueryui.com/ : the UI libraryhttp://jquerymobile.com/ : the mobile frameworkhttp://www.manning.com/bibeault/ : best book on jQuery (in my opinion)
Getting StartedWhat you will need :Core library (comes as MIN and FULL versions)Download from http://docs.jquery.com/Downloading_jQueryUse CDN hosted files (MS, Google, jQuery)Visual Studio Intellisense SupportDownload from http://code.jquery.com/jquery-1.4.1-vsdoc.jsUIDownload from  http://jqueryui.com/downloadThis gives you js PLUS cssMobileDownload from  http://jquerymobile.com/download/You will need js PLUS cssNow that you have the JS and CSS, refer to them and lets get started !!!<script type="text/javascript" src="jquery.js"></script>
$ sign$ is an alias to refer to the jQuery library
You can use either jQuery OR $ to refer to the library
Two main modes of usage
$. : Typically for utility methods
$( : Typically for selectors and document ready method$(document).ready“As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. ”Flavors of usage :$(document).ready(function() { //DO SOMETHING});$(function() {	//DO SOMETHING});function readyFn() { // code to run when the document is ready } $(document).ready(readyFn);
SelectorsUsed to select element(s) from DOM based on “selection criteria”Gets us “wrapped set” of matching elements$( selector, <context>)selector defines the matching criteriaContext is optional parameter to restrict are where to match and is a selector in itself. By default, context is the entire documentVarious types of selectorsCSSChild, Attributes, ContainerPositionCustom$(“img”) – will select all images in the DOM$(“img”, “#containerDiv”) – will select all images present in the element by name containerDiv
CSS Selectors$(“a”) 			This selector matches all link (<a>) elements.$(“#specialID”)		This selector matches elements that have an id of specialID$(“.specialClass”)	This selector matches elements that have the class of specialClass$(“ a#specialID.specialClass”)This selector matches links with an id of specialID and a class of specialClass$(“p a.specialClass”)This selector matches links with a class of specialClass declared within <p> elements.$("div,span,p.myClass") selects all divs, spans and paragraphs which have class myClass
Child, attributes, container selectors$(“p > a”)	 	matches links that are direct children of a <p> element$("a[href^='http://']")		matches links that start with http://$("a[href$='.pdf']")		matches links that end with .pdf$("a[href*='google.com']")	matches links that contain google.com$("a[href='append.htm']")	matches links that point to append.htmlli:has(a)			matches all <li> elements that contain an <a>
Position selectors$("td:first")		first td of the context (will select single element)$("td:last“)		last td of the context (will select single element)$("td:even“)		all even td of the context $("td:odd“)		all odd td in the context$("td:eq(5)“)		6th td in the context (index from 0)$("td:gt(5)“)		7th to last td in the context (index from 0)$("td:lt(5)“)		1st  to 5th td in the context (index from 0)$("td:first-child“)	first td of each row (will select first column)$("td:last-child“)	last td of each row (will select last column)$("td:nth-child(3)“)	3rd td of each row (will select 3rd column, index from 1)$("td:nth-child(even)“) 	all even td in each row (will select all even columns)$("td:nth-child(odd)“)	 all odd td in each row (will select all odd columns)
Custom selectors$(“input:checkbox”)		all checkboxes$(“input:radio:checked”)		all radiobuttons that are checked$(“input:checkbox:not(:checked):enabled”)	all checkboxes that are not checked and are enabled
Managing wrapped set$("td").get(0)		gets 1st element from wrapped set (index from 0)$("td").toArray()[1]	converts wrapped set to array of elements and gets 2nd element$("td").eq(2)		gets 3rd element from wrapped set but as wrapped element.$("td").first()		gets first element from wrapped set but as wrapped element.$("td").last()		gets last element from wrapped set but as wrapped element.$("td").size()		gets the size of the wrapped set$('img').index($('#findMe'))		gets the index of image with ID findMe in the set of all images$('img[alt]').add('img[title]') 		<img> elements that have either an alt or a title$('img[title]').not('[title*=puppy]')	gets all images with have title but not containing puppy$("input:checkbox").filter(":checked")  filters list of all checkboxes to give only the ones that are checked$("li").filter(".dummyClass").hide().end().addClass("selectedItem") hide the li with dummy class and add selectedItem class to all li
.each()each(iterator)	Traverses all elements in the matched set invoking the passed iterator function for each.iterator (Function) A function called for each element in the matched set. The parameter passed to this function is set to the zero-based index of the element within the set, and the element itself is available as the this property of the function.Returns wrapped set (important for chaining)$('img').each(function(n){	this.alt='This is image['+n+'] with an id of '+this.id;});
Attributes$("#txtDemo").attr("data-custom")		gets the value of attribute "data-custom"$("#txtDemo").removeAttr("data-custom")		removes the attribute "data-custom"$("#txtDemo").attr("data-custom", "updated value for attribute")		sets value of attribute "data-custom" to updated value for attribute"		this can be used to add an attribute OR update the value of existing attribute$("#txtDemo").attr({ title: 'updated value for title', value: 'content changed as well', 'data-custom' : 'updated value of custom attrib again' }) sets multiple attributes$("input:checkbox").removeAttr('disabled');	enables all checkbox$("input:checkbox").attr('disabled', true);	disables all checkoxes$("a[href^=http://]").attr("target","_blank")	all links starting with http will open in new window
Styling$("#trFirstRow").addClass("selectedItem")		add class selectedItem to trFirstRow$("#trFirstRow").removeClass("selectedItem")				remove class selectedItem to trFirstRow$("#trFirstRow").addClass("customClass")		add class customClass to trFirstRow$("#trFirstRow").removeClass("customClass")		remove class customClass to trFirstRow$("#trFirstRow").toggleClass("customClass")				toggles the class customClass to trFirstRow (add if not present, remove if present)$("#trFirstRow").css({border: '1px solid Black',background: 'Blue',color: 'White'})	add multiple css attributes$("#trFirstRow").css("background-color")		gets the css attribute's value$("#trFirstRow").height(80)				sets height$("#trFirstRow").width() 				gets width
Content$("#demoDiv").html()			gets the html content of the div (formatting info as well)$("#demoDiv").html("This is a formatted <b>HTML</b> content which has some <i>random formatting.</i> updated")sets the html content of the div. So we will see HTML in bold$("#demoDiv").text()			gets the content as text (no formatting information)$("#demoDiv").text("This is a formatted <b>HTML</b> content which has some <i>random formatting.</i> updated but as you see, formatting is gone");		sets text content of div. No formatting$("input:text").val("Updated the content ") ; VAL is only for form elementsSets the value of textboxes. .val() will get us the content$("input:button").eq(0).val("GET VALUE");Sets the value of button (text that we see). .val() will get us the current content$("select").val("tiger");	selects the option with value tiger in the select control
Creating new elementHtml content within $(“”) generates a new element which then needs to be added to DOM using append / prepend or any such methodFlavorsSpecifying the full html : $('<p>This is a new paragraph</p>');Specifying the attributes : $('<a/>', { 	html : 'This is a <strong>new</strong> link',    'class' : 'new',href : 'foo.html'});
Modifying the DOM tree$("#coffee").append("<li>" + $("#drinkName").val() + "</li>")<li id="coffee">Coffee</li> becomes <li id="coffee">Coffee<li>test</li></li>$("#coffee").prepend("<li>" + $("#drinkName").val() + "</li>");<li id="coffee">Coffee</li> becomes <li id="coffee"><li>test</li>Coffee</li>$("#coffee").after("<li>" + $("#drinkName").val() + "</li>"); <li id="coffee">Coffee</li> becomes <li id="coffee">Coffee</li> <li>Test</li> $("#coffee").before("<li>" + $("#drinkName").val() + "</li>"); <li id="coffee">Coffee</li> becomes <li>Test</li> <li id="coffee">Coffee</li>$("#blackTea").remove();removes the element from DOM$("#tea").clone().appendTo("#milk") clones tea and appends to milk$("#tea").wrap("<div></div>") adds a wrapper div element over tea (<div><li id="tea">Tea</li></div>)
DOM Traversal$("#subChildLI").children()	gets all direct children$("#subChildLI").closest("tr")	gets closest tr in DOM hierarchy$("#subChildLI").parent()	gets immediate parent$("#subChildLI").parents("ul")	gets all ul parents in DOM hierarchy (filtered)$("#subChildLI").parents()	gets all parents in the DOM hierarchy$("#subChildLI").siblings()	gets all siblings of selected element$("#subChildLI").prev()		gets previous sibling$("#subChildLI").next()		gets next sibling
Utility functionsFunctions we looked at so far operated on jQuery object if you willThese are all in the $.fn namespacecalled on jQuery selectionsautomatically receive and return the selection as thisAnother set of functions are called Utility methodsThese are in the $ namespacedo not work with selectionsthey are not automatically passed any arguments, and their return value will vary
Utility functions : browser support$.browser	provides flags that help in determining the user agent$.browser.versiongives the version of the browser’s rendering engine$.browser.msie / firefox / opera / safari is set to true based on user agent$.cssFloat, $.opacity etc used to determine browser’s support for various capabilities$.boxModelBox model : true if the page is using the W3C standard box model and false if the page is using the Internet Explorer box model (traditional). Under the W3C box model, the size of the content of the element is 180 by 72 pixels exactly as specified by the width and height values. The padding and the border are applied outside this 180 by 72 pixel box, resulting in a total footprint of 210 by 102 pixels for the entire element. When the traditional box model is used, the entire element is rendered in the 180 by 72 pixel box defined by the width and height attributes, reducing the size of the content to 150 by 42 pixels
Utility functions (contd.)$.noConflict()	sets $ free for usage by another library. Post this, use jQuery instead of $$.paramconverts string / object to query string taking care of formatting and encodingOriginal object		{firstName: 'Yogi',lastName: 'Bear',streetAddress: '123 Anywhere Lane',city: 'Austin',state: 'TX',postalCode: '78701'}serialized to query stringfirstName=Yogi&lastName=Bear&streetAddress=123+Anywhere+Lane&city=Austin&state=TX&postalCode=78701$.makeArray(object)  Converts the passed array-like object into a JavaScript array$.unique(array)  Given an array of DOM elements, returns an array of the unique elements in the original array $.parseJSON(string) parses jsonString and gives object evaluating the string
Manipulating objects and collections$.trim(“   text with spaces   “)		trims the string$.each(anyArray, function (n, value){	//here you get the index and value for each element	});$.each(anyObject, function (name, value){	//here you get name and value one by one	});$.inArray(56, originalArray)	checks for number 56 as an element in the array. If present, returns the index ELSE returns -1
Manipulating objects and collectionsFilter an array using $.grepvargrepArray = $.grep(originalArray, function (a) { return a > 50; });
varanotherGrepArray = $.grep(originalArray, function (value) {                return value > 50;            }, true); 	Note that the filter is works as an iterator calling the function for each row and adding to the result set IF function returns TRUE	In the second approach, we have option to say if we want to invert the filteringTranslate an array using $.map which applies a function to each element in the original array to get the result setvarvaluesArray = $.map(stringArray, function (value) {var result = new Number(value);                return isNaN(result) ? null : 5*result;});
Animations and effectsFor examples, we will refer to source code from the book : http://localhost/jqia2.source/chapter5/lab.effects.htmlEach of these methods optionally take a speed param – number in milliseconds or text like Slow, Normal, Fastcall back function reference that will be invoked once effect is completefadeTo needs opacity to be defined$(“#sampleDiv”).hide(“slow”) 	hides the element$(“#sampleDiv”).show(“slow”) 	shows the element$(“#sampleDiv”).toggle(“slow”) 	toggles the visibility state of the element$(“#sampleDiv”).fadeIn(“slow”) 	hidden element is shown by changing opacity$(“#sampleDiv”).fadeOut(“slow”) 	element is hidden by changing opacity$(“#sampleDiv”).fadeTo(“slow”, 0.5) 	changes the opacity to 0.5$(“#sampleDiv”).slideUp(“slow”) 	collapses the element$(“#sampleDiv”).slideDown(“slow”) 	expands the element$(“#sampleDiv”).slideToggle(“slow”) 	toggles the slide of the element
Creating custom effectsanimate(properties, speed) can be used to make custom effectsProperties is an object specifying the target values for various css propertiesSpeed specifies the time needed to reach this target stateAdditionally, we can specify callback as well$('.animateMe').each(function(){$(this).animate({width: $(this).width() * 2,height: $(this).height() * 2},	2000);});
EventsBinding events, handling event object and passing data to events have been chaotic conventionallyjQuery gives multiple handy ways to make this simplerBind, unbindInspect event instanceTriggerWhen binding, we can bind multiple handlers in two waysSpecifying all of them by bind() will fire them all when the event is triggeredUsing toggle() will fire them as if a circular list – each trigger picks up the next handler
Binding eventsBind a function directly to the eventbind  method that takes event name(s), data to be passed to event handler and callback function (reference or inline definition)Many common events are present by name to be either specified in bind method OR use the first approach – blur, click, dblclick, change, focus etcSimilar to bind(), one() can be used – this unbinds the handler after being called onceRemove a handler by unbind() method$('p').click(function() {    console.log('click');});$('p').bind('click', function() {    console.log('click');})$('input').bind(    'click change',  // bind to multiple events    { foo : 'bar' }, // pass in data    function(eventObject) {        console.log(eventObject.type, eventObject.data);    });
Trigger eventsBroadly 3 ways Invoke the trigger() method which accepts event name and dataInvoke triggerHandler() method which operates as trigger() BUT doenst propagate the eventAs seen with binding, we can call the event name directly for some methods – click(), blur(), focus()When binding, we can bind multiple handlers
TemplatesHelps create a HTML template that can be repeatedly usedPlugin that you will need to download from https://github.com/jquery/jquery-tmpl/blob/master/jquery.tmpl.min.jsTwo small stepsDefine the markup and associate to a nameApply template When we pass an object, its properties can be accessed by ${NAME}When we pass a list, the template iterates over each object in the list<script id="summaryTemplate" type="text/x-jquery-tmpl">	<li>${Name}</li> </script> function renderList() { 	$( "#summaryTemplate" ).tmpl( movies ).appendTo( "#moviesList" ); 	//OR : $.tmpl( "summaryTemplate", movies ).appendTo( "#movieList" );}
AjaxGET vs POSTUse GET only for “getting” data, pass criteria as query string, typically gets cachedUse POST for CUD (CRUD-R)Data types (for GET, this is return data, for POST this is send data)text, html, xml, json, jsonp, scriptCore method : $.ajax({});url specifies the URL for get / postdataType specifies the type of data expected to be sent / received in POST / GETdata specifies the data being POSTed. Can also be query stringtype specifies the type of call – POST / GET typicallysuccess is a pointer to the callback function when response is 200 OKerror and complete are pointers to functions on error and complete – more like catch and finally in try-catch blocks.Convenience methods that default some of the properties : $.get, $.post, $.getJSONAccepturl (mandatory), data, dataType and success as params
Ajax GETvarnoteData;function DemoLoadData() {            $.ajax({                type: "GET",url: "http://localhost/NoteApp/NoteService/Service.svc/GetNoteData",                cache: false,                success: LoadDataSucceeded,                error: LoadDataFailed            });}function LoadDataSucceeded(msg) {            alert(msg);            $("#jsonContainer").val(msg);noteData = JSON.parse(msg); }function LoadDataFailed(result) {            alert(result.status + ' ' + result.statusText);}
Ajax POSTfunction SaveNoteData() {varobjectData = JSON.stringify(noteData);            $.ajax({url: "http://localhost/NoteApp/NoteService/Service.svc/SaveNoteData",                type: 'post',dataType: 'json',contentType: 'application/json; charset=utf-8',                data: JSON.stringify(noteData),                success: function (res) {                    alert(res);                },                error: function (xhr) {                    if (xhr.responseText) {var err = JSON.parse(xhr.responseText);                        if (err)                            alert(err);                        else                            alert({ Message: "Unknown server error." })                    }                    return;                }            });        }
Ajax convenience methods // get plain text or html$.get(‘myservice.svc/GetAllData', { employeeID: 1234 }, function(resp) {    console.log(resp);});// get JSON-formatted data from the server$.getJSON(' myservice.svc/GetAllDataJSON', function(resp) {    $.each(resp, function(k, v) {        console.log(k + ' : ' + v);    });});
jQuery Plug-inA new method that we use to extend jQuery's prototype objectCan be used privately or shared with othersSince extending prototype, it is available for all jQuery objectsGuidelinesName the file as jquery.PLUGINNAME.jsName in file and your method’s name should be sameKeep track of developer community to avoid name conflicts Wrap the actual plugin in an immediately-invoked function:	(function($){	    //...	}(jQuery));Because of closure, this creates a "private" scope of $ hence allowing us to extend jQuery without risk of $ being overwritten by another library
jQuery Plug-in developmentUtility functions$.functionName = function(params){function-body};Invoked as $.functionName(params)Wrapper methodsThese will operate on DOM and will need to support chaining $.fn.wrapperFunctionName = function(params){function-body};Invoked as $(selector).functionName(params)(function ($) {        $.fn.makeItBlueOrRed = function () {returnthis.each(function () {$(this).css('color', $(this).is('[id]') ? 'blue' : 'red');            });        };    })(jQuery);(function($){	$.say = function(what) { alert('I say '+what); }})(jQuery);
jQuery UIhttp://jqueryui.com/demos/Use jQuery UI to get lot of available controls that can enhance the UI on your pageThe link takes you to demo page to show what is available from jQueryBeyond this, you can find much more by just searching for jQuery UI Plugins for almost anything you want
What's on offer?
Third party controlsAn example : http://www.flexigrid.info/Starting from as simple a code usage as $('.flexme').flexigrid();
Ad

More Related Content

What's hot (20)

jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
Bedis ElAchèche
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Jquery
JqueryJquery
Jquery
Girish Srivastava
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Siva Arunachalam
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
Marc Grabanski
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
Simon Willison
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoid
dmethvin
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
Simon Willison
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
Angel Ruiz
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgets
velveeta_512
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas
 
jQuery
jQueryjQuery
jQuery
Vishwa Mohan
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
Mark Rackley
 
Learn css3
Learn css3Learn css3
Learn css3
Mostafa Bayomi
 
jQuery
jQueryjQuery
jQuery
Mohammed Arif
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
Kaloyan Kosev
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
Sudar Muthu
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
Arwid Bancewicz
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
Simon Willison
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoid
dmethvin
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
Angel Ruiz
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgets
velveeta_512
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
Mark Rackley
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
Kaloyan Kosev
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
Sudar Muthu
 

Similar to Introduction to jQuery (20)

J Query
J QueryJ Query
J Query
Compare Infobase Limited
 
J Query Public
J Query PublicJ Query Public
J Query Public
pradeepsilamkoti
 
J query training
J query trainingJ query training
J query training
FIS - Fidelity Information Services
 
Jquery 2
Jquery 2Jquery 2
Jquery 2
Manish Kumar Singh
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
Muhammad Afzal Qureshi
 
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
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
MobME Technical
 
jQuery
jQueryjQuery
jQuery
Ivano Malavolta
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
Allegient
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Seble Nigussie
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
guest5d87aa6
 
jQuery - Tips And Tricks
jQuery - Tips And TricksjQuery - Tips And Tricks
jQuery - Tips And Tricks
Lester Lievens
 
Jquery
JqueryJquery
Jquery
Zoya Shaikh
 
JQuery
JQueryJQuery
JQuery
DevTalk
 
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdfUnit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
Unit 1 - What is jQuery_Why jQuery_Syntax_Selectors.pdf
RAVALCHIRAG1
 
Jquery
JqueryJquery
Jquery
Pankaj Srivastava
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
orestJump
 
jQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusionjQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusion
Denard Springle IV
 
jQuery
jQueryjQuery
jQuery
Julie Iskander
 
J Query
J QueryJ Query
J Query
ravinxg
 
Ad

Recently uploaded (20)

Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Ad

Introduction to jQuery

  • 2. AgendaWhat is jQueryGetting Startedthe famous $ signselectors and managing wrapped setManipulating attributes, class, content for elementsDOM traversal and manipulationsome utility functionseffects provided by jQuery coreevents and getting close to unobtrusive JavaScripttemplateAjaxjQueryPluginjQuery UIjQuery Mobile
  • 3. What is jQueryPer their website, “jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.”It was first released in Jan 2006, current release is 1.4.4Lightweight (24KB), CSS3 compliant, Cross BrowserA separate UI library and Mobile LibraryUsed by over 41% of the 10,000 most visited websites (majors like Google, Dell, Bank of America, NBC, Netflix … )Supported by Microsoft as well Per http://trends.builtwith.com/, jQuery and jQuery UI constitute around 50% of all JS libraries used on the web
  • 4. Other JS librariesSWFObject is a small Javascript file used for embedding Adobe Flash content (http://code.google.com/p/swfobject/ )Prototype : http://www.prototypejs.org/The Yahoo! User Interface (YUI) Library : http://developer.yahoo.com/yui/script.aculo.us : http://script.aculo.us/MooTools : http://mootools.net/ Google Mashup Editor (GME) : retired but still in use http://code.google.com/gme/
  • 5. jQuery Resourceshttp://jquery.com/ : this is the core website.http://docs.jquery.com/Main_Page : developer’s starting pagehttp://docs.jquery.com/Tutorials : tutorialshttp://plugins.jquery.com/ : plugin repositoryhttp://jqueryui.com/ : the UI libraryhttp://jquerymobile.com/ : the mobile frameworkhttp://www.manning.com/bibeault/ : best book on jQuery (in my opinion)
  • 6. Getting StartedWhat you will need :Core library (comes as MIN and FULL versions)Download from http://docs.jquery.com/Downloading_jQueryUse CDN hosted files (MS, Google, jQuery)Visual Studio Intellisense SupportDownload from http://code.jquery.com/jquery-1.4.1-vsdoc.jsUIDownload from http://jqueryui.com/downloadThis gives you js PLUS cssMobileDownload from http://jquerymobile.com/download/You will need js PLUS cssNow that you have the JS and CSS, refer to them and lets get started !!!<script type="text/javascript" src="jquery.js"></script>
  • 7. $ sign$ is an alias to refer to the jQuery library
  • 8. You can use either jQuery OR $ to refer to the library
  • 9. Two main modes of usage
  • 10. $. : Typically for utility methods
  • 11. $( : Typically for selectors and document ready method$(document).ready“As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. ”Flavors of usage :$(document).ready(function() { //DO SOMETHING});$(function() { //DO SOMETHING});function readyFn() { // code to run when the document is ready } $(document).ready(readyFn);
  • 12. SelectorsUsed to select element(s) from DOM based on “selection criteria”Gets us “wrapped set” of matching elements$( selector, <context>)selector defines the matching criteriaContext is optional parameter to restrict are where to match and is a selector in itself. By default, context is the entire documentVarious types of selectorsCSSChild, Attributes, ContainerPositionCustom$(“img”) – will select all images in the DOM$(“img”, “#containerDiv”) – will select all images present in the element by name containerDiv
  • 13. CSS Selectors$(“a”) This selector matches all link (<a>) elements.$(“#specialID”) This selector matches elements that have an id of specialID$(“.specialClass”) This selector matches elements that have the class of specialClass$(“ a#specialID.specialClass”)This selector matches links with an id of specialID and a class of specialClass$(“p a.specialClass”)This selector matches links with a class of specialClass declared within <p> elements.$("div,span,p.myClass") selects all divs, spans and paragraphs which have class myClass
  • 14. Child, attributes, container selectors$(“p > a”) matches links that are direct children of a <p> element$("a[href^='http://']") matches links that start with http://$("a[href$='.pdf']") matches links that end with .pdf$("a[href*='google.com']") matches links that contain google.com$("a[href='append.htm']") matches links that point to append.htmlli:has(a) matches all <li> elements that contain an <a>
  • 15. Position selectors$("td:first") first td of the context (will select single element)$("td:last“) last td of the context (will select single element)$("td:even“) all even td of the context $("td:odd“) all odd td in the context$("td:eq(5)“) 6th td in the context (index from 0)$("td:gt(5)“) 7th to last td in the context (index from 0)$("td:lt(5)“) 1st to 5th td in the context (index from 0)$("td:first-child“) first td of each row (will select first column)$("td:last-child“) last td of each row (will select last column)$("td:nth-child(3)“) 3rd td of each row (will select 3rd column, index from 1)$("td:nth-child(even)“) all even td in each row (will select all even columns)$("td:nth-child(odd)“) all odd td in each row (will select all odd columns)
  • 16. Custom selectors$(“input:checkbox”) all checkboxes$(“input:radio:checked”) all radiobuttons that are checked$(“input:checkbox:not(:checked):enabled”) all checkboxes that are not checked and are enabled
  • 17. Managing wrapped set$("td").get(0) gets 1st element from wrapped set (index from 0)$("td").toArray()[1] converts wrapped set to array of elements and gets 2nd element$("td").eq(2) gets 3rd element from wrapped set but as wrapped element.$("td").first() gets first element from wrapped set but as wrapped element.$("td").last() gets last element from wrapped set but as wrapped element.$("td").size() gets the size of the wrapped set$('img').index($('#findMe')) gets the index of image with ID findMe in the set of all images$('img[alt]').add('img[title]') <img> elements that have either an alt or a title$('img[title]').not('[title*=puppy]') gets all images with have title but not containing puppy$("input:checkbox").filter(":checked") filters list of all checkboxes to give only the ones that are checked$("li").filter(".dummyClass").hide().end().addClass("selectedItem") hide the li with dummy class and add selectedItem class to all li
  • 18. .each()each(iterator) Traverses all elements in the matched set invoking the passed iterator function for each.iterator (Function) A function called for each element in the matched set. The parameter passed to this function is set to the zero-based index of the element within the set, and the element itself is available as the this property of the function.Returns wrapped set (important for chaining)$('img').each(function(n){ this.alt='This is image['+n+'] with an id of '+this.id;});
  • 19. Attributes$("#txtDemo").attr("data-custom") gets the value of attribute "data-custom"$("#txtDemo").removeAttr("data-custom") removes the attribute "data-custom"$("#txtDemo").attr("data-custom", "updated value for attribute") sets value of attribute "data-custom" to updated value for attribute" this can be used to add an attribute OR update the value of existing attribute$("#txtDemo").attr({ title: 'updated value for title', value: 'content changed as well', 'data-custom' : 'updated value of custom attrib again' }) sets multiple attributes$("input:checkbox").removeAttr('disabled'); enables all checkbox$("input:checkbox").attr('disabled', true); disables all checkoxes$("a[href^=http://]").attr("target","_blank") all links starting with http will open in new window
  • 20. Styling$("#trFirstRow").addClass("selectedItem") add class selectedItem to trFirstRow$("#trFirstRow").removeClass("selectedItem") remove class selectedItem to trFirstRow$("#trFirstRow").addClass("customClass") add class customClass to trFirstRow$("#trFirstRow").removeClass("customClass") remove class customClass to trFirstRow$("#trFirstRow").toggleClass("customClass") toggles the class customClass to trFirstRow (add if not present, remove if present)$("#trFirstRow").css({border: '1px solid Black',background: 'Blue',color: 'White'}) add multiple css attributes$("#trFirstRow").css("background-color") gets the css attribute's value$("#trFirstRow").height(80) sets height$("#trFirstRow").width() gets width
  • 21. Content$("#demoDiv").html() gets the html content of the div (formatting info as well)$("#demoDiv").html("This is a formatted <b>HTML</b> content which has some <i>random formatting.</i> updated")sets the html content of the div. So we will see HTML in bold$("#demoDiv").text() gets the content as text (no formatting information)$("#demoDiv").text("This is a formatted <b>HTML</b> content which has some <i>random formatting.</i> updated but as you see, formatting is gone"); sets text content of div. No formatting$("input:text").val("Updated the content ") ; VAL is only for form elementsSets the value of textboxes. .val() will get us the content$("input:button").eq(0).val("GET VALUE");Sets the value of button (text that we see). .val() will get us the current content$("select").val("tiger"); selects the option with value tiger in the select control
  • 22. Creating new elementHtml content within $(“”) generates a new element which then needs to be added to DOM using append / prepend or any such methodFlavorsSpecifying the full html : $('<p>This is a new paragraph</p>');Specifying the attributes : $('<a/>', { html : 'This is a <strong>new</strong> link', 'class' : 'new',href : 'foo.html'});
  • 23. Modifying the DOM tree$("#coffee").append("<li>" + $("#drinkName").val() + "</li>")<li id="coffee">Coffee</li> becomes <li id="coffee">Coffee<li>test</li></li>$("#coffee").prepend("<li>" + $("#drinkName").val() + "</li>");<li id="coffee">Coffee</li> becomes <li id="coffee"><li>test</li>Coffee</li>$("#coffee").after("<li>" + $("#drinkName").val() + "</li>"); <li id="coffee">Coffee</li> becomes <li id="coffee">Coffee</li> <li>Test</li> $("#coffee").before("<li>" + $("#drinkName").val() + "</li>"); <li id="coffee">Coffee</li> becomes <li>Test</li> <li id="coffee">Coffee</li>$("#blackTea").remove();removes the element from DOM$("#tea").clone().appendTo("#milk") clones tea and appends to milk$("#tea").wrap("<div></div>") adds a wrapper div element over tea (<div><li id="tea">Tea</li></div>)
  • 24. DOM Traversal$("#subChildLI").children() gets all direct children$("#subChildLI").closest("tr") gets closest tr in DOM hierarchy$("#subChildLI").parent() gets immediate parent$("#subChildLI").parents("ul") gets all ul parents in DOM hierarchy (filtered)$("#subChildLI").parents() gets all parents in the DOM hierarchy$("#subChildLI").siblings() gets all siblings of selected element$("#subChildLI").prev() gets previous sibling$("#subChildLI").next() gets next sibling
  • 25. Utility functionsFunctions we looked at so far operated on jQuery object if you willThese are all in the $.fn namespacecalled on jQuery selectionsautomatically receive and return the selection as thisAnother set of functions are called Utility methodsThese are in the $ namespacedo not work with selectionsthey are not automatically passed any arguments, and their return value will vary
  • 26. Utility functions : browser support$.browser provides flags that help in determining the user agent$.browser.versiongives the version of the browser’s rendering engine$.browser.msie / firefox / opera / safari is set to true based on user agent$.cssFloat, $.opacity etc used to determine browser’s support for various capabilities$.boxModelBox model : true if the page is using the W3C standard box model and false if the page is using the Internet Explorer box model (traditional). Under the W3C box model, the size of the content of the element is 180 by 72 pixels exactly as specified by the width and height values. The padding and the border are applied outside this 180 by 72 pixel box, resulting in a total footprint of 210 by 102 pixels for the entire element. When the traditional box model is used, the entire element is rendered in the 180 by 72 pixel box defined by the width and height attributes, reducing the size of the content to 150 by 42 pixels
  • 27. Utility functions (contd.)$.noConflict() sets $ free for usage by another library. Post this, use jQuery instead of $$.paramconverts string / object to query string taking care of formatting and encodingOriginal object {firstName: 'Yogi',lastName: 'Bear',streetAddress: '123 Anywhere Lane',city: 'Austin',state: 'TX',postalCode: '78701'}serialized to query stringfirstName=Yogi&lastName=Bear&streetAddress=123+Anywhere+Lane&city=Austin&state=TX&postalCode=78701$.makeArray(object) Converts the passed array-like object into a JavaScript array$.unique(array) Given an array of DOM elements, returns an array of the unique elements in the original array $.parseJSON(string) parses jsonString and gives object evaluating the string
  • 28. Manipulating objects and collections$.trim(“ text with spaces “) trims the string$.each(anyArray, function (n, value){ //here you get the index and value for each element });$.each(anyObject, function (name, value){ //here you get name and value one by one });$.inArray(56, originalArray) checks for number 56 as an element in the array. If present, returns the index ELSE returns -1
  • 29. Manipulating objects and collectionsFilter an array using $.grepvargrepArray = $.grep(originalArray, function (a) { return a > 50; });
  • 30. varanotherGrepArray = $.grep(originalArray, function (value) { return value > 50; }, true); Note that the filter is works as an iterator calling the function for each row and adding to the result set IF function returns TRUE In the second approach, we have option to say if we want to invert the filteringTranslate an array using $.map which applies a function to each element in the original array to get the result setvarvaluesArray = $.map(stringArray, function (value) {var result = new Number(value); return isNaN(result) ? null : 5*result;});
  • 31. Animations and effectsFor examples, we will refer to source code from the book : http://localhost/jqia2.source/chapter5/lab.effects.htmlEach of these methods optionally take a speed param – number in milliseconds or text like Slow, Normal, Fastcall back function reference that will be invoked once effect is completefadeTo needs opacity to be defined$(“#sampleDiv”).hide(“slow”) hides the element$(“#sampleDiv”).show(“slow”) shows the element$(“#sampleDiv”).toggle(“slow”) toggles the visibility state of the element$(“#sampleDiv”).fadeIn(“slow”) hidden element is shown by changing opacity$(“#sampleDiv”).fadeOut(“slow”) element is hidden by changing opacity$(“#sampleDiv”).fadeTo(“slow”, 0.5) changes the opacity to 0.5$(“#sampleDiv”).slideUp(“slow”) collapses the element$(“#sampleDiv”).slideDown(“slow”) expands the element$(“#sampleDiv”).slideToggle(“slow”) toggles the slide of the element
  • 32. Creating custom effectsanimate(properties, speed) can be used to make custom effectsProperties is an object specifying the target values for various css propertiesSpeed specifies the time needed to reach this target stateAdditionally, we can specify callback as well$('.animateMe').each(function(){$(this).animate({width: $(this).width() * 2,height: $(this).height() * 2}, 2000);});
  • 33. EventsBinding events, handling event object and passing data to events have been chaotic conventionallyjQuery gives multiple handy ways to make this simplerBind, unbindInspect event instanceTriggerWhen binding, we can bind multiple handlers in two waysSpecifying all of them by bind() will fire them all when the event is triggeredUsing toggle() will fire them as if a circular list – each trigger picks up the next handler
  • 34. Binding eventsBind a function directly to the eventbind method that takes event name(s), data to be passed to event handler and callback function (reference or inline definition)Many common events are present by name to be either specified in bind method OR use the first approach – blur, click, dblclick, change, focus etcSimilar to bind(), one() can be used – this unbinds the handler after being called onceRemove a handler by unbind() method$('p').click(function() { console.log('click');});$('p').bind('click', function() { console.log('click');})$('input').bind( 'click change', // bind to multiple events { foo : 'bar' }, // pass in data function(eventObject) { console.log(eventObject.type, eventObject.data); });
  • 35. Trigger eventsBroadly 3 ways Invoke the trigger() method which accepts event name and dataInvoke triggerHandler() method which operates as trigger() BUT doenst propagate the eventAs seen with binding, we can call the event name directly for some methods – click(), blur(), focus()When binding, we can bind multiple handlers
  • 36. TemplatesHelps create a HTML template that can be repeatedly usedPlugin that you will need to download from https://github.com/jquery/jquery-tmpl/blob/master/jquery.tmpl.min.jsTwo small stepsDefine the markup and associate to a nameApply template When we pass an object, its properties can be accessed by ${NAME}When we pass a list, the template iterates over each object in the list<script id="summaryTemplate" type="text/x-jquery-tmpl"> <li>${Name}</li> </script> function renderList() { $( "#summaryTemplate" ).tmpl( movies ).appendTo( "#moviesList" ); //OR : $.tmpl( "summaryTemplate", movies ).appendTo( "#movieList" );}
  • 37. AjaxGET vs POSTUse GET only for “getting” data, pass criteria as query string, typically gets cachedUse POST for CUD (CRUD-R)Data types (for GET, this is return data, for POST this is send data)text, html, xml, json, jsonp, scriptCore method : $.ajax({});url specifies the URL for get / postdataType specifies the type of data expected to be sent / received in POST / GETdata specifies the data being POSTed. Can also be query stringtype specifies the type of call – POST / GET typicallysuccess is a pointer to the callback function when response is 200 OKerror and complete are pointers to functions on error and complete – more like catch and finally in try-catch blocks.Convenience methods that default some of the properties : $.get, $.post, $.getJSONAccepturl (mandatory), data, dataType and success as params
  • 38. Ajax GETvarnoteData;function DemoLoadData() { $.ajax({ type: "GET",url: "http://localhost/NoteApp/NoteService/Service.svc/GetNoteData", cache: false, success: LoadDataSucceeded, error: LoadDataFailed });}function LoadDataSucceeded(msg) { alert(msg); $("#jsonContainer").val(msg);noteData = JSON.parse(msg); }function LoadDataFailed(result) { alert(result.status + ' ' + result.statusText);}
  • 39. Ajax POSTfunction SaveNoteData() {varobjectData = JSON.stringify(noteData); $.ajax({url: "http://localhost/NoteApp/NoteService/Service.svc/SaveNoteData", type: 'post',dataType: 'json',contentType: 'application/json; charset=utf-8', data: JSON.stringify(noteData), success: function (res) { alert(res); }, error: function (xhr) { if (xhr.responseText) {var err = JSON.parse(xhr.responseText); if (err) alert(err); else alert({ Message: "Unknown server error." }) } return; } }); }
  • 40. Ajax convenience methods // get plain text or html$.get(‘myservice.svc/GetAllData', { employeeID: 1234 }, function(resp) { console.log(resp);});// get JSON-formatted data from the server$.getJSON(' myservice.svc/GetAllDataJSON', function(resp) { $.each(resp, function(k, v) { console.log(k + ' : ' + v); });});
  • 41. jQuery Plug-inA new method that we use to extend jQuery's prototype objectCan be used privately or shared with othersSince extending prototype, it is available for all jQuery objectsGuidelinesName the file as jquery.PLUGINNAME.jsName in file and your method’s name should be sameKeep track of developer community to avoid name conflicts Wrap the actual plugin in an immediately-invoked function: (function($){ //... }(jQuery));Because of closure, this creates a "private" scope of $ hence allowing us to extend jQuery without risk of $ being overwritten by another library
  • 42. jQuery Plug-in developmentUtility functions$.functionName = function(params){function-body};Invoked as $.functionName(params)Wrapper methodsThese will operate on DOM and will need to support chaining $.fn.wrapperFunctionName = function(params){function-body};Invoked as $(selector).functionName(params)(function ($) { $.fn.makeItBlueOrRed = function () {returnthis.each(function () {$(this).css('color', $(this).is('[id]') ? 'blue' : 'red'); }); }; })(jQuery);(function($){ $.say = function(what) { alert('I say '+what); }})(jQuery);
  • 43. jQuery UIhttp://jqueryui.com/demos/Use jQuery UI to get lot of available controls that can enhance the UI on your pageThe link takes you to demo page to show what is available from jQueryBeyond this, you can find much more by just searching for jQuery UI Plugins for almost anything you want
  • 45. Third party controlsAn example : http://www.flexigrid.info/Starting from as simple a code usage as $('.flexme').flexigrid();
  • 46. jQuery Mobilehttp://jquerymobile.com/The above URL takes you to the home of jQuery mobile frameworkDemo pages show what this can doSince mostly uses CSS3 / HTML5, IE 7 / 8 doesn’t support thisHowever IE9 and most of other browsers – Firefox, Safari, Opera – show this correctlyGiven that most of mobile’s web browsers are supporting this, we should be good to use the power of this framework
  • 47. How does it change my UI?
  • 48. Referenceshttp://docs.jquery.com/Plugins/Authoringhttp://nsreekanth.blogspot.com/search/label/JQuery%20pluginhttp://msdn.microsoft.com/en-gb/scriptjunkie/ee730275.aspxhttp://msdn.microsoft.com/en-gb/scriptjunkie/ff848255.aspxhttp://jqfundamentals.com/book/book.htmlhttp://nsreekanth.blogspot.com/search/label/JQuery%20pluginhttp://jquery.com/ : this is the core website.http://docs.jquery.com/Main_Page : developer’s starting pagehttp://docs.jquery.com/Tutorials : tutorialshttp://plugins.jquery.com/ : plugin repositoryhttp://jqueryui.com/ : the UI libraryhttp://jquerymobile.com/ : the mobile frameworkhttp://www.manning.com/bibeault/ : best book on jQuery (in my opinion)