Embed
Email

JQuery_Guide

Document Sample

Categories
Tags
Stats
views:
5
posted:
11/19/2011
language:
English
pages:
15
JQuery

Guide









Table of Contents

INTRODUCTION ............................................................................................... 3

KEY FEATURES ................................................................................................. 4

GETTING A FEEL FOR JQUERY .......................................................................... 6

GETTING STARTED WITH SELECTORS ............................................................. 7

THE $(DOCUMENT).READY() HANDLER ............................................................ 9

EVENT HANDLING .......................................................................................... 10

PLUG-INS FOR EVERYTHING ELSE ................................................................. 11









Page 1 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

USING JQUERY TO CONSUME ASP.NET JSON WEB SERVICES ........................ 13

USING JQUERY TO DIRECTLY CALL ASP.NET AJAX PAGE METHOD ................. 16

USEFUL LINKS .............................................................................................. 17









Introduction



jQuery is a fast, concise, JavaScript Library that simplifies how you traverse

HTML documents, handle events, perform animations, and add Ajax interactions to

your web pages”.It is basically a JavaScript framework for writing huge task of

JavaScript with few lines of code. It was released in January 2006 at BarCamp NYC by

John Resig.

A big part of the appeal of jQuery is that it allows you to elegantly (and

efficiently) find and manipulate HTML elements with minimum lines of code. jQuery

supports this via a nice "selector" API that allows developers to query for HTML

elements, and then apply "commands" to them. One of the characteristics of jQuery

commands is that they can be "chained" together - so that the result of one command

can feed into another. jQuery also includes a built-in set of animation APIs that can be

used as commands. The combination allows you to do some really cool things with

only a few keystrokes.









Page 2 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

Key Features



 DOM Element Selectors



jQuery Selectors allow to select DOM elements so that we can apply

functionality to them with jQuery‟s operational methods. jQuery uses a CSS 3.0 syntax

(plus some extensions) to select single or multiple elements in a document. Using CSS

means that we use selector syntax we‟re probably already familiar with from HTML

styling and even if not it‟s fairly easy to pick up the key CSS selector features. Using

CSS syntax you can select elements by id, CSS class, attribute filters, by relationship

to other element and even filter conditions that can be chained together. A simple

example: It's trivial to select all 2nd column TD elements in a table with a simple

selector like this: $("#gdEntries td:nth-child(2)").





 The jQuery Object: The Wrapped Set



Selectors result in a jQuery object that is known as the Wrapped Set, which is

an array like structure that contains each of the selected DOM elements. You can

iterate over the wrapped set like an array or access individual elements via the indexer

( $(sel)[0] for example). More importantly though you can also apply jQuery functions

against all the selected elements.





 Wrapped Set Operations



The real power of the wrapped set comes from being able to apply jQuery

operations against all selected DOM elements simultaneously. The jQuery.fn object

exposes about 100 functions that can operate on the matched set and allow to

manipulate and retrieve information from the selected DOM objects in batch. For

example, you can easily manipulate all alternate rows in a table by adding a CSS class

with $("#gdEntries tr:odd").addClass("gridalternate"). The .addClass() function is

applied against each of the matched elements with one command. Intuitive methods

allow you do to things like get and set .css() styles directly including smart logic that

accounts for browser differences of assignment types (number and string translations

mostly) and values (opacity does the right thing on all browsers). You can set and

retrieve attributes with .attr(), or retrieve or set a value with .val(), .text() or .html().

You can clone selected DOM elements or create new elements from HTML text used as

a selector and inject them into the document with methods like .appendTo(),

.prependTo() or reversely use a parent element to .append() or .prepend() the new or

selected element(s). There are basic but useful effects methods that can be applied to









Page 3 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

.show() and .hide() elements in a smart way that checks for opacity, display and

visibility and adjusts all to show or hide elements. All of this and much more can be

done against all of the selected elements.

Most wrapped set operations are also chainable so that they return the jQuery

wrapped set object as a result. This means you can chain together many methods in a

single command. Effectively this means you can select once, and operate many times

against the same object and even filter or expand the wrapped set with methods like

.find(), .filter() or .add().

The beauty of many of these functions is that they do things you actually want

to do, and they are intuitively overloaded. Methods like .val() or .text() act both as

retrieval and setter methods. Methods that deal with numeric values can take either

text or numeric values. CSS assignments to browser dependent tags are automatically

fixed up. Although the number of functions provided by jQuery is relatively small,

many of the functions provide overloaded functionality to perform intuitive behaviors.

The end result is that you have a relatively small API to learn, but a much broader

range of functionality that is available on it.





 Simplified Event Handling



Much of what is done in JavaScript code from DOM manipulation to AJAX calls

are handled asynchronously and unfortunately the DOM implementations for event

handling vary considerably between browsers. jQuery provides an easy mechanism for

binding and unbinding events and providing a normalized event model for all supported

browsers that makes it very easy to handle events and hook result handlers. All events

are called in the context of the element that caused the event and they receive a fixed

up and browser normalized event object that is consistent.





 Small Footprint



jQuery is a fairly compact base library yet it‟s feature packed with stuff you'll

actually use. In my relatively short time of jQuery use I've gone through well over

85% of the jQuery functions with my code, which points at how useful the library is. All

this functionality ends up in a compressed size of just around 16k (94k uncompressed

with comments). For that you get selectors, a whole slew of operations that can be

performed on the wrapped set, DOM normalization for most browsers, Ajax

functionality, a host of utility functions for object/array manipulation and a number of

basic effect functionality. Given the high utilization of jQuery in my use this 16k of

script download provides a tremendous amount of “Bang for the Buck”.





 Easy Plug-in Extensibility



jQuery is a language and DOM extension library and it provides a core set of

useful features. It's small and tightly focused on providing core functionality and no

more. For everything else jQuery provides a very easy plug-in API that has spawned

hundreds of plug-ins for almost every conceivable common operation you might think

up to perform on a set of DOM elements.









Page 4 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

jQuery’s API allows extending the core jQuery object’s operations

simply by creating a function and passing the jQuery Wrapped set as a

parmeter. In this way plug-ins receive the wrapped set and can operate on it

and participate in the jQuery chaining. This very simple but powerful plug-in

model is very easy to work with and likely the key of why so many plug-ins

exist and jQuery has become so popular so quickly. If you need some

specialty functionality, chances are that a plug-in already exists with the

functionality you're looking for. And if it doesn't, it's easy enough to creating

it yourself with the help of jQuery or another plug-in as a baseline.Getting a

feel for jQuery





jQuery is a client script library and so you have to add a script reference to your

page. You can download the latest version of jQuery from the jQuery site at

www.jQuery.com.



There are many ways that you can include jQuery into your page:



 Reference a local copy via tag in the page

 Reference a local copy with ScriptManager

 Embed script from Resource using the ClientScript object

 Reference a remote copy from jQuery.com or Google Ajax API



Usually for web applications like in Asp.net, use the following that in header section to

include the Jquery file into the application.























Page 5 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

Getting started with Selectors







Selectors are the key that make jQuery useful. You start by selecting content

and then applying a jQuery function to it. Here are a few examples that hopefully are

fairly self-explanatory.



You can select a single element:



$("#gdEntries").css("border", "solid 1px navy");



Or select by class (.):



$(".gridalternate").css("background", "lightsteelblue ");



or from a couple of classes (, like in CSS separates multiple selectors):



$(".gridrow,.gridalternate").attr("tag", "row");



You can also select elements (plain element) and apply filters to the elements. The

following selects all buttons in a document and attaches a click handler:



$("input:button ").click(function(event) { alert("clicked"); });



A more complex example might select all rows in a table:



$("#gdEntries>tbody>tr").css("border", "solid 1px red");



Here are a few of the common jQuery/CSS selectors types that can be applied :





Example Description

Selector



Element $("td") Select an HTML element tag









Page 6 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

#id $("#divMessage") Selects an element by its id





.cssclass $(".gridalternate") Selects a CSS style





selector,selector $("input:button,input:t Multiple comma separated selectors

ext") can be combined into a single

selection.





ancestor descendant $("#divMessage a") A space between

selectors/elements/tags finds nested

elements. This syntax is similar to Css

ancestor descendant syntax.







parent > child $("p > b") Matches all immediate children of an

> child element or selector expression that

match the right element/selector.





prev ~ siblings $("#row_11:nth- Matches the next siblings at the

~ siblings child(2)~td") sample level as the preceeding

$("~td") expression. Example, matches 3-nth

columns of a table row. Best used as

a find() or filter() against an existing

jQuery instance.





prev + nextsibling $("#tdMoneyCol+td") Matches the following sibling. Works

$("+td") best with find() or filter() against an

+ nextsibling existing jQuery object.





:filter $("input:button") : applies filters to the query. jQuery

support CSS 3 filters plus a number of

custom filters.



Examples:

:not,:button,:visible,:hidden,:checked

,:first,nth-

child(1),:has,:is,:contains,:parent









Page 7 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

[@attribute] $("p[class=gridalternat Selects an attribute of an element

e] = equals string

^= startswith



$= endswith



*= contains









THE $(DOCUMENT).READY() HANDLER







.ready() is a jQuery event handler and your first exposure to how to handle events

with jQuery. This particular event handler lets you know when the Document is ready

to be accessed and scripts have completed loading. This ensures that your code can

access all DOM elements and script code reliably. A .ready() handler can be placed

anywhere on the page and you can even have multiple ready handlers in the page.



This tag is run on the page load. So you can call the functions that are required to call

on page load in this handler.



e.g. In below example, I want to set the css to Grid on page load then I will do the

following way -







$(document).ready( function() {



$("#gdEntries tbody tr:even")



.addClass("gridalternate")



.css("border","solid 1px lightgrey");



});













Page 8 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

EVENT HANDLING







Event handling is one of the nicest aspects of jQuery because it makes the process

easy and consistent across browsers. jQuery provides the high level .bind() and

.unbind() functions to generically attach and detach event handlers on matched sets.

In addition most of the common events like click, key and mouse events have

dedicated handler functions like .click(), .mousedown(), change() and .keydown().

jQuery event handlers simply take a function as a parameter and jQuery tracks these

handlers so that they can also be unbound later. It can‟t be much easier than this. In

addition there‟s .one() which fires an event exactly once then disconnects the handler

and .toggle() which toggle between alternating clicks, and .trigger() which can trigger

events on elements.



jQuery also provides a common model for event handlers:



 The this pointer always equals the element the event fired on



 An event object is always passed as a parameter



 Event object is a cross-browser „normalized‟



e.g. Suppose you have one button on your page







and you want to write the click event for this button using Jquery then it is written as

follow -



$(#button1).click(function() {



alert('test');

});







Page 9 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

PLUG-INS FOR EVERYTHING ELSE







Plug-ins are one of the main reasons that jQuery has become so popular. Part of

the reason for this is that jQuery has a super simple API for plug-ins. There is a

jQuery.fn property which hosts any operational functions that can operate on the

matched set.



You can download the Jquery plug-in from -



http://plugins.jquery.com/



Example for using Dialog box plug-in in your application -



1. Download the dialog plugin files of Jquery from above link.



2. Add those files to your application



3. Add the links for those files into your application like-



" type="text/javascript">







4. Add following code to script tag on the page where you want to implement the

Jquery dialog box . Here 'dialog' is div present on your page.



$(function(){







Page 10 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

$("#dialog").dialog

({

modal: true,

autoOpen: false,

bgiframe: true,

closeOnEscape: true

});

});



5.



6. To open this dialog box use the following function -



$('#dialog').dialog('open');



7. To close the dialog box use



$('#dialog').dialog('close');



More help for this plug in is avaliable on Jquery site -



http://docs.jquery.com/UI/Dialog









USING JQUERY TO CONSUME ASP.NET JSON WEB SERVICES







Using jQuery‟s Ajax method provides a clean syntax to interact with ASP.NET Web

Services. To use Jquery with Web services, we have required web services with JSON

serialized.



1. Create the JSON serialized web service -



Firstly, add the web service to your application. Then there you will see



_



tag in webservice page. This tag is commented. So uncomment that tag to

make the web service JSON serialized.



Then create the object that you want to show the data from that onto the page.

e.g. You want to show the details for the student then create the Student class

like









Page 11 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

Public Class Student



Private _RollNumber As Integer



Private _Name As String





Public Property RollNumber() As Integer



Get

Return _ RollNumber

End Get

Set(ByVal value As Integer)

_ RollNumber = value

End Set

End Property



Public Property Name() As String

Get

Return _ Name

End Get

Set(ByVal value As String)

_ Name = value

End Set

End Property



End Class



Fill the student object as per your requirement with data from database. Then write

the web service method to return this object.



_



Public Function GetStudentData() As List(Of Student)

Dim objStudent As New List(Of Student)

Return objStudent

End Function



2. Call this web service method into the .aspx page using Jquery as follow -







jQuery(document).ready(



function()

{

ShowData();









Page 12 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

}

);





function ShowData()



{



var url = "" ;

$.ajax({

type: "POST",

url: url,

data: "{}",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function(data)

{

$(ShowStudentData(data.d));

},

error: function(data)

{ alert('fail'); }

}

);



}



function ShowStudentData(var DataTable)

{

// Show the student data into your required object e.g. Table or Grid.



}











Page 13 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

USING JQUERY TO DIRECTLY CALL ASP.NET AJAX PAGE METHOD







It is same as call method from web service. Here give the page name and

method name to call the required method.



$.ajax({



type: "POST",



url: "PageName.aspx/MethodName",



data: "{}",



contentType: "application/json; charset=utf-8",



dataType: "json",



success: function(msg) {









Page 14 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0

// Do something interesting here.



}



});









USEFUL LINKS



http://en.wikipedia.org/wiki/JQuery



http://docs.jquery.com/Main_Page



http://ldeveloper.blogspot.com/2008/10/intro-to-jquery-basic-tutorial.html



http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=508



http://www.webreference.com/programming/asp/jquery/



http://www.dev102.com/2008/04/30/call-aspnet-webmethod-from-jquery/



http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-

methods/



http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/



http://jqueryui.com/demos/dialog/



http://www.secondpersonplural.ca/jqgriddocs/index.htm









Page 15 of 15 Clarion Technologies Pvt. Ltd, Pune Version 1.0



Other docs by Stariya Js @ B...
Lab2_Fishing_lab_pack
Views: 0  |  Downloads: 0
JMK sample legal brief
Views: 1  |  Downloads: 0
DriveQ
Views: 0  |  Downloads: 0
cybersecurity_reform_-_senate_bill_eyes
Views: 0  |  Downloads: 0
Opening and Marketing
Views: 0  |  Downloads: 0
Making_it_Work_notes
Views: 0  |  Downloads: 0
First Announcement 7th ISFS_
Views: 0  |  Downloads: 0
as90173
Views: 0  |  Downloads: 0
VNAfashionshow2010
Views: 0  |  Downloads: 0
By registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!