jquery fundamentals

41
jQuery jQuery Fundamentals, DOM, Events, AJAX, UI Fundamentals, DOM, Events, AJAX, UI Doncho Minkov Doncho Minkov Telerik Mobile Development Course Telerik Mobile Development Course mobiledevcourse.teleri mobiledevcourse.teleri k.com k.com Technical Trainer Technical Trainer http://www.minkov.it

Upload: doncho-minkov

Post on 27-Jan-2015

1.982 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: jQuery Fundamentals

jQueryjQueryFundamentals, DOM, Events, AJAX, UIFundamentals, DOM, Events, AJAX, UI

Doncho MinkovDoncho Minkov

Telerik Mobile Development CourseTelerik Mobile Development Coursemobiledevcourse.telerimobiledevcourse.telerik.comk.com

Technical TrainerTechnical Trainerhttp://www.minkov.it

Page 2: jQuery Fundamentals

Table of ContentsTable of Contents jQuery FundamentalsjQuery Fundamentals

Selection and DOM ManipulationSelection and DOM Manipulation Events and ChainingEvents and Chaining

AJAXAJAX jQuery AJAX MethodsjQuery AJAX Methods Executing AJAX RequestsExecuting AJAX Requests

jQuery UIjQuery UI jQuery WidgetsjQuery Widgets Implementing Drag and DropImplementing Drag and Drop

2

Page 3: jQuery Fundamentals

What is jQuery?What is jQuery?The world’s most popular JavaScript The world’s most popular JavaScript

librarylibrary

Page 4: jQuery Fundamentals

What is jQuery?What is jQuery? jQuery is a cross-browser JavaScript library jQuery is a cross-browser JavaScript library 

Designed to simplify the client-side Designed to simplify the client-side scripting of HTMLscripting of HTML

The most popular JavaScript library in use The most popular JavaScript library in use todaytoday

Free, open source softwareFree, open source software jQuery's syntax is designed to make it jQuery's syntax is designed to make it

easier toeasier to Navigate a document and select DOM Navigate a document and select DOM

elements elements Create animationsCreate animations Handle eventsHandle events Develop AJAX applicationsDevelop AJAX applications

4

Page 5: jQuery Fundamentals

What is jQuery? (2)What is jQuery? (2) jQuery also provides capabilities for jQuery also provides capabilities for

developers to create plugins fordevelopers to create plugins for Low-level interaction and animationLow-level interaction and animation Advanced effects and high-level, theme-Advanced effects and high-level, theme-

able widgetsable widgets Creation of powerful and dynamic web Creation of powerful and dynamic web

pagespages Microsoft adopted jQuery within Visual Microsoft adopted jQuery within Visual

StudioStudio Uses in Microsoft's ASP.NET Uses in Microsoft's ASP.NET

AJAX Framework and ASP.NET MVC AJAX Framework and ASP.NET MVC FrameworkFramework 5

Page 6: jQuery Fundamentals

Why jQuery is So Why jQuery is So Popular?Popular?

Easy to learn Easy to learn Fluent programming styleFluent programming style

Easy to extendEasy to extend You create new jQuery plugins by You create new jQuery plugins by

creating new JavaScript functionscreating new JavaScript functions Powerful DOM Selection Powerful DOM Selection

Powered by CSS 3.0Powered by CSS 3.0 LightweightLightweight Community Support Community Support

Large community of developers and Large community of developers and geeksgeeks 6

Page 7: jQuery Fundamentals

How to Add jQuery to a How to Add jQuery to a Web Site?Web Site?

Download jQuery files fromDownload jQuery files from http://www.jquery.comhttp://www.jquery.com

Self hostedSelf hosted You can choose to self host the You can choose to self host the .js.js file file E.g. E.g. jquery-1.5.jsjquery-1.5.js or or jquery-1.5.min.jsjquery-1.5.min.js

Use it from CDN (content delivery Use it from CDN (content delivery network)network)

Microsoft, jQuery, Google CDNsMicrosoft, jQuery, Google CDNs e.g. http://code.jquery.com/jquery-e.g. http://code.jquery.com/jquery-

1.5.min.js,1.5.min.js, http://ajax.microsoft.com/ajax/jquery/http://ajax.microsoft.com/ajax/jquery/

jquery-1.5.min.jsjquery-1.5.min.js 7

Page 8: jQuery Fundamentals

Fundamentals of Fundamentals of jQueryjQuerySelecting, Adding, Removing DOM Selecting, Adding, Removing DOM ElementsElements

Page 9: jQuery Fundamentals

Selecting and Doing Selecting and Doing SomethingSomething

With jQuery you typically find With jQuery you typically find something, then do something with something, then do something with itit Syntax for finding items is the same Syntax for finding items is the same

as the syntax used in CSS to apply as the syntax used in CSS to apply stylesstyles

There are lots of different jQuery There are lots of different jQuery methods to do with the selected methods to do with the selected elementselements

// Finding the item// Finding the item$("#something").hide();$("#something").hide();

// Doing something with the found item// Doing something with the found item<div id="something"></div><div id="something"></div>

9

Page 10: jQuery Fundamentals

Show Hide ElementsShow Hide ElementsLive DemoLive Demo

Page 11: jQuery Fundamentals

jQuery FundamentalsjQuery Fundamentals When selecting with jQuery you can When selecting with jQuery you can

end up with more than one elementend up with more than one element Any action taken will typically affect Any action taken will typically affect

all the elements you have selectedall the elements you have selected

<div class="myClass foo bar"></div><div class="myClass foo bar"></div><div class="baz myClass"></div><div class="baz myClass"></div><div class="bar"></div><div class="bar"></div>

//...//...$('.myClass').hide(); // will hide both $('.myClass').hide(); // will hide both elementselements//...//...

11

Page 12: jQuery Fundamentals

DOM ManipulationDOM Manipulation

With jQuery HTML adding elements With jQuery HTML adding elements can be done on the flycan be done on the fly Very easilyVery easily Can be appended to the pageCan be appended to the page Or to another elementOr to another element

Still selecting something Still selecting something (brand new), then doing (brand new), then doing something something

$('<ul><li>Hello</li></ul>').appendTo('body');$('<ul><li>Hello</li></ul>').appendTo('body');

12

Page 13: jQuery Fundamentals

// Before// Before<div><div> <p>Red</p> <p>Red</p> <p>Green</p><p>Green</p></div></div>

// Removing elements// Removing elements$('p').remove();$('p').remove();

Removing ElementsRemoving Elements

13

You can also remove elements You can also remove elements from the DOMfrom the DOM Just as easyJust as easy

// After// After<div><div></div></div>

Page 14: jQuery Fundamentals

Selecting Multiple Selecting Multiple ElementsElements

Live DemoLive Demo

Page 15: jQuery Fundamentals

With jQuery binding to events is With jQuery binding to events is very easyvery easy We can specify a click handler We can specify a click handler

For example by using the click For example by using the click methodmethod

The above code will bind the The above code will bind the myClickHandlermyClickHandler function to all function to all anchors with a class of anchors with a class of tabtab

jQuery EventsjQuery Events

// Binding an event// Binding an eventfunction() myClickHandler { function() myClickHandler { // event handling code// event handling code $(this).css('color', 'red');$(this).css('color', 'red');};};$('a.tab').click(myClickHandler);$('a.tab').click(myClickHandler);

15

Page 16: jQuery Fundamentals

Functions in JavaScript could be Functions in JavaScript could be anonymousanonymous

This is the same exact functionality This is the same exact functionality as the previous exampleas the previous example This is important because in the This is important because in the

previous example we polluted the previous example we polluted the global scope with a new function global scope with a new function namename Can be dangerous as someone could Can be dangerous as someone could

overwrite your function with their overwrite your function with their own accidentallyown accidentally

jQuery EventsjQuery Events

16

$('a.tab').click(function() { $('a.tab').click(function() { // event handling code// event handling code $(this).css('color', 'red');$(this).css('color', 'red');});});

Page 17: jQuery Fundamentals

jQuery Method jQuery Method ChainingChaining

With jQuery many methods allow With jQuery many methods allow chainingchaining Chaining is where you can continue Chaining is where you can continue

to "chain" on methods one after to "chain" on methods one after anotheranother

As an example, the As an example, the addClassaddClass method will add the class 'method will add the class 'oddodd' in ' in the code belowthe code below

Then return the jQuery collection Then return the jQuery collection We can immediately chain on the We can immediately chain on the

""clickclick" event" event ClickClick then operates on the odd then operates on the odd

rows by adding a rows by adding a clickclick handlerhandler to to each of themeach of them

$('tr:odd').addClass('odd')$('tr:odd').addClass('odd') .click(function () { alert('you clicked a .click(function () { alert('you clicked a tr!'); });tr!'); });

17

Page 18: jQuery Fundamentals

Chaining MethodsChaining MethodsLive DemoLive Demo

Page 19: jQuery Fundamentals

jQuery Stack jQuery Stack ArchitectureArchitecture

Some jQuery methods chain and Some jQuery methods chain and return a new collection of elements return a new collection of elements ''FindFind' and '' and 'FilterFilter' are two examples' are two examples

jQuery holds on to the previous jQuery holds on to the previous collections, essentially creating a collections, essentially creating a stack set to store themstack set to store them

19

Page 20: jQuery Fundamentals

jQuery Stack jQuery Stack Architecture (2)Architecture (2)

Methods like Methods like FindFind and and FilterFilter create a new collection which is create a new collection which is added to the stackadded to the stack Older collections are pushed Older collections are pushed

further 'further 'downwarddownward' on the stack' on the stack You can get a previous collection You can get a previous collection

back from the stack by using the back from the stack by using the end()end() method method

20

$('body') // [body]$('body') // [body] .find('p') // [p, p, p] > [body].find('p') // [p, p, p] > [body] .find('a') // [a, a] > [p, p, p] > [body].find('a') // [a, a] > [p, p, p] > [body] .addClass('foo').addClass('foo') .end() // [p, p, p] > [body].end() // [p, p, p] > [body] .end() // [body].end() // [body]

Page 21: jQuery Fundamentals

$('tr')$('tr') .filter(':odd').filter(':odd') .addClass('myOddClass').addClass('myOddClass') .end().end() .filter(':even').filter(':even') .addClass('myEvenClass');.addClass('myEvenClass');

jQuery & Chaining and jQuery & Chaining and ArchitectureArchitecture

This is a popular use that shows This is a popular use that shows both chaining and the stack both chaining and the stack architecturearchitecture

21

Page 22: jQuery Fundamentals

jQuery & Chaining and jQuery & Chaining and Architecture (2)Architecture (2)

1.1. First select all rowsFirst select all rows

2.2. Then filter to only the odd rows Then filter to only the odd rows

1.1.The odd rows are placed on the top of the The odd rows are placed on the top of the stackstack

2.2.The 'The 'all rowsall rows' collection is now ' collection is now 'pushed'pushed downwarddownward''

3.3.Add a class to the odd rowsAdd a class to the odd rows

3.3. We call endWe call end Throws away the 'Throws away the 'odd rowsodd rows' collection ' collection Grabs the next element in the stack Grabs the next element in the stack

The 'The 'all rowsall rows' collection' collection

Then filter to find Then filter to find even rowseven rows

1.1.We add a class to the even rowsWe add a class to the even rows 22

Page 23: jQuery Fundamentals

jQuery Stack jQuery Stack ArchitectureArchitecture

Live DemoLive Demo

Page 24: jQuery Fundamentals

Dynamically Dynamically Assigning a Assigning a

ClassClassLive Live DemoDemo

Page 25: jQuery Fundamentals

jQuery AJAXjQuery AJAX

Page 26: jQuery Fundamentals

AJAX FundamentalsAJAX Fundamentals AJAX is acronym of AJAX is acronym of Asynchronous Asynchronous

JavaScript and XMLJavaScript and XML Technique for background loading of Technique for background loading of

dynamic content and data from the server dynamic content and data from the server sideside

Allows dynamic client-side changesAllows dynamic client-side changes Two styles of AJAXTwo styles of AJAX

Partial page rendering – loading of HTML Partial page rendering – loading of HTML fragment and showing it in a fragment and showing it in a <div><div>

JSON service – loading JSON object and JSON service – loading JSON object and client-side processing it with JavaScript / client-side processing it with JavaScript / jQueryjQuery 26

Page 27: jQuery Fundamentals

jQuery AjaxjQuery Ajax You can use jQuery Ajax to seamlessly You can use jQuery Ajax to seamlessly

integrate with server side functionalityintegrate with server side functionality jQuery makes simple the asynchronous server jQuery makes simple the asynchronous server

callscalls jQuery.ajax(…)jQuery.ajax(…)

The core method for using AJAX functionalityThe core method for using AJAX functionality

The shortcut methods use it 'under the hood'The shortcut methods use it 'under the hood'

Thus it can do everythingThus it can do everything

$.get(…)$.get(…) and and $.post(…)$.post(…) Executes a server-side request and returns a Executes a server-side request and returns a

resultresult

The HTTP action that will occur is POST or GETThe HTTP action that will occur is POST or GET27

Page 28: jQuery Fundamentals

jQuery Ajax (2)jQuery Ajax (2) $.getJSON(<url>)$.getJSON(<url>)

Uses the GET HTTP action and inform the Uses the GET HTTP action and inform the server to send back JSON-serialized dataserver to send back JSON-serialized data

$(…).load($(…).load(<url><url>)) Gets HTML from the server and loads it Gets HTML from the server and loads it

into whatever you have selected (e.g. a into whatever you have selected (e.g. a <div><div>))

Note that jQuery AJAX does not use a Note that jQuery AJAX does not use a selection (except for selection (except for .load(…).load(…) method) method) With certain jQuery methods there is not With certain jQuery methods there is not

a logical reason to make a selection first a logical reason to make a selection first Most AJAX methods fall into that categoryMost AJAX methods fall into that category

28

Page 29: jQuery Fundamentals

jQuery Ajax – $jQuery Ajax – $(…).load()(…).load()

Example of dynamically loaded AJAX Example of dynamically loaded AJAX content:content:

$(…).load(<url>)$(…).load(<url>) Gets an HTML fragment from the server Gets an HTML fragment from the server

and load it into whatever you have and load it into whatever you have selectedselected

Data could come from a PHP script, a static Data could come from a PHP script, a static resource or an ASP.NET pageresource or an ASP.NET page Note that the server should return a page Note that the server should return a page

fragmentfragment

If it returns a whole HTML page, then we If it returns a whole HTML page, then we are going to have some invalid HTML!are going to have some invalid HTML! 29

$('#myContainer').load('home/$('#myContainer').load('home/myHtmlSnippet.html');myHtmlSnippet.html');

Page 30: jQuery Fundamentals

jQuery Ajax – ExamplejQuery Ajax – Example

30

<button>Perform AJAX Request</button><button>Perform AJAX Request</button>

<script type="text/javascript"><script type="text/javascript"> $("button").click(function() {$("button").click(function() { $.ajax({$.ajax({ url: "data.html",url: "data.html", success: function(data){success: function(data){ $('#resultDiv').text(data);$('#resultDiv').text(data); }} });}); });});</script></script>

<div id="resultDiv">Result will be shown <div id="resultDiv">Result will be shown here</div>here</div>

Note that Note that data.htmldata.html will not be will not be loaded unless the script comes from loaded unless the script comes from a Web servera Web server AJAX URL should reside on the same AJAX URL should reside on the same

Web serverWeb server

Page 31: jQuery Fundamentals

jQuery AJAX: JSON-jQuery AJAX: JSON-Style AJAX and Style AJAX and

Partial RenderingPartial RenderingLive DemoLive Demo

Page 32: jQuery Fundamentals

jQuery UIjQuery UI

Page 33: jQuery Fundamentals

jQuery UIjQuery UI jQuery UI is a separate JavaScript jQuery UI is a separate JavaScript

librarylibrary Lives in a separate Lives in a separate .js.js file file

jQuery UI contains three different jQuery UI contains three different groups of additionsgroups of additions Effects: draggable, droppable, resizable, Effects: draggable, droppable, resizable,

selectable, sortableselectable, sortable Interactions: show & hide additions, Interactions: show & hide additions,

color animation, easingscolor animation, easings Widgets: Accordion, Autocomplete, Widgets: Accordion, Autocomplete,

Button, Datepicker, Dialog, Progressbar, Button, Datepicker, Dialog, Progressbar, Slider, TabsSlider, Tabs 33

Page 34: jQuery Fundamentals

WidgetsWidgets jQuery widgets are UI components jQuery widgets are UI components

for the Webfor the Web All widgets are theme-able!All widgets are theme-able!

Adding most widgets is very simple Adding most widgets is very simple in code:in code:

34

$("input:text.date").datepicker();$("input:text.date").datepicker();

$("#someDiv").accordion();$("#someDiv").accordion();

var langs = ["C#", "Java", "PHP", "Python", var langs = ["C#", "Java", "PHP", "Python", "SQL"];"SQL"];$("#langBox").autocomplete({ source: langs });$("#langBox").autocomplete({ source: langs });<div id="dialog" title="a title"><p>Some <div id="dialog" title="a title"><p>Some text</p></div>text</p></div>$("#dialog").dialog();$("#dialog").dialog();$("#slider").slider();$("#slider").slider();

Page 35: jQuery Fundamentals

jQuery UIjQuery UILive DemoLive Demo

Page 36: jQuery Fundamentals

jQuery UIjQuery UIDrag-and-DropDrag-and-Drop

Live DemoLive Demo

Page 37: jQuery Fundamentals

jQuery FundamentalsjQuery Fundamentals

Questions?Questions?

http://schoolacademy.telerik.com

Page 38: jQuery Fundamentals

ExercisesExercises1.1.Open the file Open the file /exercises/index.html/exercises/index.html in your in your

browserbrowser Select all of the div elements that have a class Select all of the div elements that have a class

of "of "modulemodule".".

Come up with three selectors that you could use Come up with three selectors that you could use to get the third item in the to get the third item in the #myList #myList unordered unordered listlist

Select the label for the search input using an Select the label for the search input using an attribute selectorattribute selector

Count hidden elements on the page Count hidden elements on the page (hint: .(hint: .lengthlength))

Count the image elements that have an alt Count the image elements that have an alt attributeattribute

Select all of the odd table rows in the table bodySelect all of the odd table rows in the table body38

Page 39: jQuery Fundamentals

Exercises (2)Exercises (2) Open the file Open the file /exercises/index.html /exercises/index.html in your in your

browserbrowser Select all of the image elements on the Select all of the image elements on the

pagepage

Log each image's alt attributeLog each image's alt attribute

Select the search input text box, then Select the search input text box, then traverse up to the form and add a class to traverse up to the form and add a class to the form.the form.

Select the list item inside Select the list item inside #myList#myList that has that has a class of "a class of "currentcurrent""

Remove that class from itRemove that class from it

Add a class of "Add a class of "currentcurrent" to the next list item" to the next list item 39

Page 40: jQuery Fundamentals

Exercises (3)Exercises (3) Open the file Open the file /exercises/index.html /exercises/index.html in in

your browseryour browser Select the select element inside Select the select element inside

#specials#specials

Traverse your way to the submit button.Traverse your way to the submit button.

Select the first list item in the Select the first list item in the #slidesh#slideshow ow elementelement

Add the class "Add the class "currentcurrent" to it, and then add " to it, and then add

a class of "a class of "disableddisabled" to its sibling elements" to its sibling elements

40

Page 41: jQuery Fundamentals

Exercises (4)Exercises (4) Open the file /exercises/index.html in your Open the file /exercises/index.html in your

browserbrowser Add five new list items to the end of the Add five new list items to the end of the

unordered list unordered list #myList#myList

Remove the odd list itemsRemove the odd list items

Add another Add another h2h2 and another and another paragraphparagraph to the to the last last div.modulediv.module

Add another option to the select elementAdd another option to the select element

Give the option the value "Give the option the value "WednesdayWednesday""

Add a new Add a new div.modulediv.module to the page after the last to the page after the last oneone

Put a copy of one of the existing images inside of Put a copy of one of the existing images inside of

itit 41