Sie sind auf Seite 1von 59

The Magic Of

Sathish Chandra
Sanga
24/09/2012

Setting Expectations

This session is for Learners & Practitioners


JavaScript vs jQuery
Explore jQuery's history.
How jQuery works.
Get jQuery on your page.
Selectors n Filters
Events n Effects
Ajax
Plug-ins

About Me

Sathish Chandra Sanga


Email:
sathishchandra.s@cognizant.com

JavaScript Vs jQuery

What is Java Script?


Client Side Scripting Language
Prototype based OO Language
Essential for modern web Applications
Weakly Typed
Worlds Worst named Language
Totally unrelated to Java

Issues with Java


Script?

Dom Navigations
Browser Differences
Tedious
Time Consuming
Error Prone
Browser DOM really sucks, and
this is where jQuery comes to
rescue.

This session is about improving your

Quality of Life !

A Quality of Life by
jQuery
Just Hiding divs with JavaScript
divs= document.getElementByTagName(div);
for(i=0; i<divs.length; i++){
divs[i].style.display = none;
}

Hiding divs with jQuery


$(div).hide();
Very compact and fluent programming model

?What is jQuery

What is jQuery?
jQuery is JavaScript framework.
Its a Open source JS Library.
It's a light-weight library (31KB,
Minified and Gzipped, v1.7)
Easy and fast HTML DOM Selection
Cross browser compatible

Advantages of jQuery
Well documented
Simplifies Interaction b/w HTML & JS.
Developer community & Online
presence
Extensible
CSS like Syntax
Works with other libraries
ExtJS, Scriptaculous ,Prototype , Mootools

Tons of Plugins
Very compact and fluent programming model

Whos using jQuery?

Google
Microsoft
Twitter
Mozilla
Apple
flipKart
ASK

IBM
Amazon
Digg
Wordpress
eBay
ESPN

jQuerys History
jQuery was first released in 2006
Created by John Resig from Mozilla.

Getting Started

Import JQuery
Download the latest version from http://jquery.com
<html>
<head>
<script type="text/javascript" src="jquery1.7.min.js" />

Alternately, you can also import from hosts.


<script type="text/javascript" src =
http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.mi
n.js
" />

jQuery Core Concepts

Magic - $()
Since the jQuery() function is called so
often, the $ variable is set up as an alias to
jQuery
If youre also using another library, you can
revert to the previous $ function with
jQuery.noConflict();
Create , Manipulate, Selects

elements

HTML&DOM

IDs, Classes and Tags


An ID is a unique identifier to an element
Each element can have only one ID
Each page can have only one element with that ID

Classes are NOT unique


You can use the same class on multiple elements.
You can use multiple classes on the same
element.

Pass a selector to $()


$(#myID) $(.myClass)
(div)

jQuery Mantra
Every operation boils down to:
Find some HTML stuff
Do something to it

Find

Do

$
(div).addClass(whiteBorder
)
GET >> ACT

3 Major Concepts of jQuery

The $() function

Get > Act

Chainability

Setting up jQuery
(function($) {

// defines $ as the jQuery shortcut variable

// functions and custom plugins here

$(function() {

// shortcut for jQuery's onReady function

// place initialization bindings here

});
})(jQuery);

// pass in the global jQuery object

// Full Syntax

$(document).ready(function(){

});

jQuery Selectors

Selectors
Basic Selectors:
By ID

$(#div1)

By Class

$(.classA)

By Tag

$(div)

<div id=div1
class=classA>XYZ</div>

Combination &
Hierarchy
// find by id + by class
$(#content, .menu)
// multiple combination
$(h1, h2, h3, div.content)
$(table td)
// descendants
$(tr > td)
// children
$(label + input)
// next
$(#content ~ div) // siblings

Selection Index &


Visibility

$(tr:first) // first element


$(tr:last) // last element
$(tr:lt(2))
// index less than
$(tr:gt(2))
// index gr. than
$(tr:eq(2))
// index equals
$(div:visible) // if visible
$(div:hidden) // if not

Forms Selectors &


Filters

$(input:checkbox)// checkboxes
$(input:radio) // radio buttons
$(:button)
// buttons
$(:text) // text inputs
$(input:checked)
$(input:selected)
$(input:enabled)
$(input:disabled)

//
//
//
//

checked
selected
enabled
disabled

SELECTORS DEMO

Selector pitfalls
Don'ts Dos
$(div#myId)
$(#myId)
$(.myclass #myId)
$(#myId)
$(.myclass)
$(#nearestId
.myClass)
$(#parentId #myId)
$(#myId)
$(span .myclass)
$(.myClass) $
(#myID)
and many more

Attributes
.atttr()

.addClass()
.hasClass()
.removeAttr()
.html()
.val()
and many more

( http://api.jquery.com/category/attributes/ )

Attributes
Get
.attr(id)
.attr(id, myId)
.html()
.html(<p>Hi</p>
.val()
.css(color)
.width()

Set

.val(100)
.color(red)
.width(100)

Traversing
.parent()
.children()
.siblings()
.next()
.find()
.closest()
and many more
(http://api.jquery.com/category/traversing/ )

Manipulation
.append()
.appendTo()
.prepend()
.prependTo()
.remove()
.empty()
and many more
(http://api.jquery.com/category/manipulation/ )

jQuery Events

Events
When the DOM is ready
$(document).ready(function(){
//
});
Fires when the document is ready for
programming.
Uses advanced listeners for detecting.

Events
Possible event values:
blur, focus, load, resize, scroll, unload,
beforeunload, click, dblclick, mousedown,
mouseup, mousemove, mouseover, mouseout,
mouseenter, mouseleave, change, select,
submit, keydown, keypress, keyup, error
// attach / trigger

elem.click(fn) / elem.click()

Events
$(div).trigger(click);

Triggers browsers event action as well.


Can trigger custom events.
Triggered events bubble up.
// execute always
$(div).bind(click, fn);
// execute only once
$(div).one(click, fn);

Live Events
// attach live event
(div).live(click, fn);
// detach live event
(div).die(click, fn);

Currently supported events:


click, dblclick, mousedown, mouseup, mousemove,
mouseover, mouseout, keydown, keypress, keyup

EVENTS DEMO

Effects

Effects
.hide()
.show()
.slideUp()
.slideDown()
.toggle()
.fadeIn()
.fadeOut()
.animate()
and more (http://api.jquery.com/category/effects/ )

Effects
// just show $(div).show();
// slow=600ms $(div).show(slow);
// hide fast, fast=200ms $(div).hide(fast);
// hide or show in 100ms $(div).toggle(100);
$(div).slideUp();
$(div).slideDown(fast);
$(div).slideToggle(1000);
$(div).fadeIn(fast);
$(div).fadeOut(normal);
$(div).fadeTo (fast, 0.5);

Animation Effects
// .animate(options, duration)
$(div).animate({
width: 90%,
opacity: 0.5,
borderWidth: 5px
}, 1000);
// chaining animation

$(div).animate({width: 90%},100)
.animate({opacity: 0.5},200)
.animate({borderWidth: 5px});

Animation Styles

backgroundPosition
borderWidth
borderBottomWidth
borderLeftWidth
borderRightWidth
borderTopWidth
borderSpacing
margin
marginBottom
marginLeft
marginRight
marginTop
outlineWidth
padding
paddingBottom
paddingLeft
paddingRight
paddingTop

height
width
maxHeight
maxWidth
minHeight
minWidth
font
fontSize
bottom
left
right
top
letterSpacing
wordSpacing
lineHeight
textIndent

EFFECTS DEMO

AJAX

Source: w3schools.com

AJAX
.ajax()
.load()
.get()
.post()
.getJSON()
.getScript()
and many more
(http://api.jquery.com/category/ajax/ )

AJAX Loading
Content
$(div).load(content.htm);
// passing parameters
$(#content).load(getcontent.jsp,
{id:33,
type:main});

AJAX GET & POST


$.get(test.jsp, {id:1},
function(data){alert(data);});
$.post(test.jsp, {id:1},
function(data){alert(data);});

- $.ajax({url:"test1.txt",
success:function(result){
$("div").html(result);
}});

JSON Service Call


$. getJSON(users.aspx, {id:1},
function(users)
{
alert(users[0].name);
});
$.ajax({ url : zventsUrl,
dataType: "jsonp",
success: myZventsSuccessHandler });

Ajax Params

$.ajax, $.ajaxSetup

beforeSend
contentType
data
dataType
error
processData
success
timeout
type
url

AJAX DEMO

jQueryUI Plug-in
To build highly interactive web applications.
. Date Picker
. Tabs
. Accordion
. Progress Bar
. Slider
. Dialog
. Drag & Drop
and many more(http://http://jqueryui.com)

jQueryUI Sample
Codes
Date Picker
$( "#textBoxId" ).datepicker();
http://jqueryui.com/demos/datepicker/

Progress Bar
$( "#progress" ).progressbar({ value:
37 });
http://jqueryui.com/demos/progressbar/

Tabs
$( "#tabs" ).tabs();
http://jqueryui.com/demos/tabs/

dataTable Plug-in
.
.
.
.

Makng tables very easy


Pagination
fly-filtering
Sorting

.Source Ajax file , Server-side , JS


Array
and many more(http://www.datatables.net)

dataTable
incorporation
. I already had a table
- $(document).ready(function() {
('#myTable').dataTable(); //default Options
} );
- $(document).ready(function() {
$('#myTable').dataTable({
"bPagination": false }); //no Pagination
} );

dataTable
incorporation
-

$(document).ready(function() { $
('#myTable').dataTable({
"bPagination": false,
"aoColumns": [
{"sType": "num-html"},//Number Column
{"sType": "date"},//date Column
{"bSortable": false} ]//no Sorting
});
} );

dataTable Params

Whole Table
bAutoWidth
bFilter
bPaginate
bLengthChange
bSort
bStateSave
sScrollX

aoColumns
bSearchable
bSortable
bVisible
sType
sWidth

Good to Check
jQuery Forum ( http://forum.jquery.com/)
Documentation ( http://docs.jquery.com/ )
dataTable Plugin (http://www.datatables.net/ )
Auto-Complete
(http://archive.plugins.jquery.com/project/jam
es )
jQuery UI (http://jqueryui.com/ )
Plugins (http://plugins.jquery.com/ )
For Practice(www.w3schools.com )

Thank you

Das könnte Ihnen auch gefallen