jQuery_PPT's - WordPress.com

advertisement
RAJASEKHAR K
Whats the problem with
JavaScript?
JavaScript is a weakly typed, classless,
prototype based OO language, that can
also be used outside the browser. It is not
a browser DOM.
This session is about improving
your Quality of Life !
What is jQuery?
What is jQuery?
• jQuery is JavaScript library.
• It's a light-weight library (19kb minified and GZIPed)
• Easy and fast HTML DOM Selection
• Built to work on all modern browsers
(IE6+, FF 2.0+, Safari 3.0+, Opera 9+, Chrome 1.0+)
•
Handle events
Make AJAX calls
• It's Open Source
Why use jQuery ?
How do you locate elements with a specific
class?
How do you handle events in a
cross-browser manner?
How do you apply styles to
multiple elements?
How many hours have you
spent dealing with cross browser
issues?
Introduction to jQuery
A Quality of Life by jQuery
$(“#firstName”).text(“Joe Black”);
$(“button”).click(function() {alert “Clicked”;});
$(“.content”).hide();
$(“#main”).load(“content.htm”);
$(“<div/>”).html(“Loading…”).appendTo(“#content”);
Very compact and fluent programming model
Reference it in your markup
<script src=“jquery.js”/>
You can also reference it from Google
<script src=“http://ajax.googleapis.com/
ajax/libs/jquery/1.2.6/
jquery.min.js”>
</script>
Common jQuery Mistakes
•
•
•
•
•
Be courageous to remove jQuery
Not using latest version of jQuery
Not using minified version of jQuery library
Not loading jQuery from Google CDN
Not loading jQuery locally when CDN fails
<script type="text/javascript”
src=" http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
document.write(unescape("%3Cscript src='Scripts/jquery.1.9.0.min.js'
type='text/javascript'%3E%3C/script%3E"));
}
</script>
• Not using selectors efficiently
• Using jQuery selectors repeatedly
• Not checking while using various plugins
The Magic $() function
Fired when the document is ready for
programming.
full syntax:
$(document).ready(function(){…});
Simply :
$(function(){…});
Avoid $() conflict with other frameworks
var foo = jQuery.noConflict();
// now foo() is the jQuery main function
foo(“div”).hide();
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("p").text("jQuery is still
working!");
});
});
jQuery Selectors
All Selector
$(“*”)
// find everything
Selectors return a pseudo-array of jQuery elements
$(document).ready(function(){
$("button").click(function(){
$("*").hide();
});
});
Basic Selectors
By Tag:
$(“div”)
// <div>Hello jQuery</div>
By ID:
$(“#usr”)
// <span id=“usr”>John</span>
By Class:
$(“.menu”)
// <ul class=“menu”>Home</ul>
Yes, jQuery implements CSS Selectors!
More Precise Selectors
$(“div.main”)
// tag and class
$(“table#data”) // tag and id
Combination of Selectors
// find by id + by class
$(“#content, .menu”)
// multiple combination
$(“h1, h2, h3, div.content”)
Hierarchy Selectors
$(“table td”)
// descendants
$(“tr > td”)
// children
$(“label + input”)
// next
$(“#content ~ div”)
// siblings
$("ul.topnav > li").css("border", "3px double red");
Selection Index Filters
$(“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
$( "td:gt(4)" ).css( "backgroundColor", "yellow" );
$('li').filter(':even').css('background-color', 'red');
Attribute Filters
$(“div[id]”)
// has attribute
$(“div[dir=‘rtl’]”)
// equals to
$(“div[id^=‘main’]”)
// starts with
$(“div[id$=‘name’]”)
// ends with
$(“a[href*=‘msdn’]”)
// contains
$('input[name*=“JavaScript"]').val(‘jQuery!');
Forms Selectors
$(“input:checkbox”)
// checkboxes
$(“input:radio”)
// radio buttons
$(“:button”)
// buttons
$(“:text”)
// text inputs
Forms Filters
$(“input:checked”)
// checked
$(“input:selected”)
// selected
$(“input:enabled”)
// enabled
$(“input:disabled”)
// disabled
<input type="checkbox" name="newsletter" value="Hourly"
checked="checked">
Find Dropdown Selected Item
<select name=“cities”>
<option value=“1”>Tel-Aviv</option>
<option value=“2” selected=“selected”>Yavne</option>
<option value=“3”>Raanana</option>
</select>
$(“select[name=‘ddl’] option:selected”).val()
Document Traversal
Traversing HTML
.next(expr)
// next sibling
.prev(expr)
// previous sibling
.siblings(expr) // siblings
.children(expr) // children
.parent(expr)
// parent
$("p").next(".selected").css("background", "yellow");
Check for expression
$(“table td”).each(function() {
if ($(this).is(“:first-child”)) {
$(this).addClass(“firstCol”);
}
});
HTML Manipulation
Setting multiple attributes
$(“img”).attr({
“src” : “/images/smile.jpg”,
“alt” : “Smile”,
“width” : 10,
“height” : 10
});
CSS Manipulations
// get style
$(“div”).css(“background-color”);
// set style
$(“div”).css(“float”, “left”);
// set multiple style properties
$(“div”).css({“color”:”blue”,
“padding”: “1em”
“margin-right”: “0”,
marginLeft: “10px”});
Events
Handling Events using JavaScript
Question:
What type of JavaScript code do you write to
handle a button click event ?
Answer :
It depends on browser...!!!
Event Attachment Techniques
• Most Browsers:
myButton.addEventListener('click',function(){ },false);
myButton.attachEvent('onClick',function(){
• Internet
Explorer (IE8 and Opera) });
jquery Event Model Benifits
• Events notify a program that a user performed
some type of action
• jQuery provides a cross browser event model
that works in IE, Chrome,Opera,Safari,Firefox
and more
• jQuery event model is simple to use and
provides a compact syntax
Attach Event
$(“#myID”).click(function(){
alert(‘The element ID Clicked’);
});
// execute always
$(“div”).bind(“click”, fn);
// execute only once
$(“div”).one(“click”, fn);
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
(or any custom event)
Using Delegate()
•
The delegate() method attaches one or more event handlers for specified elements that are
children of selected elements, and specifies a function to run when the events occur.
•
Event handlers attached using the delegate() method will work for both current and FUTURE
elements (like a new element created by a script).
$(document).ready(function(){
$("div").delegate("p","click",function(){
$("p").css("background-color","pink");
});
});
Delegated Events with jQuery on() method
•
on() is introduced in 1.7 version, which provides all functionality for
attaching event handlers.
And it has made other event handler event like live() and delegate() dead.
This method was introduced due to performance issue with live()method.
•
•
$(document).ready(function () {
$(document).on("click","div", function(){
$('<div>Dynamic Div</div>').appendTo('body');
});
});
Using Hover
• This example highlights #target on
mouseenter and sets it back to white on
mouseleave
$('#target').hover(function()
{
$(this).css('background-color', '#00FF99');
},
function()
{
$(this).css('background-color', '#FFFFFF');
});
Alternate Hover Example
• Another option is
$(selector).hover(handlerInOut);
• Fires the same handler for mouseenter and
mouseleave events
• Used with jQuery's toggle methods:
$('p').hover(function() {
$(this).toggleClass('over');
});
This code will toggle the class applied to a paragraph
element
Effects
Showing or Hiding Element
$(“div”).show();
// hide fast, fast=200ms
$(“div”).hide(“fast”);
// hide or show in 100ms
$(“div”).toggle(100);
$(“div”).slideUp();
$(“div”).slideDown(“fast”);
Chaining Animation
$(“div”).animate({width: “90%”},100)
.animate({opacity: 0.5},200)
.animate({borderWidth: “5px”});
By default animations are queued and than
performed one by one
AJAX with jQuery
$.ajax()
AJAX = Asynchronous JavaScript and XML.
$.ajax() is arguably the most revolutionary jQuery function.
It provides us with means of dynamically loading content, scripts and data and
using them on our live web page.
In short; AJAX is about loading data in the background and display it on the
webpage, without reloading the whole page.
Examples of applications using AJAX: Gmail, Google Maps, Youtube, and
Facebook tabs.
jQuery Ajax Features
• jQuery allows Ajax requests to be made from a
page:
• Allows parts of a page to be updated
• Cross-Browser Support
• Simple API
• GET and POST supported
• Load JSON, XML, HTML or even scripts
Using load()
• $(selector).load(url,data,callback) allows HTML content to
be loaded from a server and added into a DOM object:
$(document).ready(function(){
$('#HelpButton').click(function(){
$('#MyDiv').load('HelpDetails.html');
});
});
Using get()
• $.get(url,data,callback,datatype) can retrieve data from a
server:
$.get('HelpDetails.html', function (data)
{
$('#OutputDiv').html(data);
});
Using post()
• $.post(url,data,callback,datatype) can post data to a
server and retrieve results:
$.post('GetCustomers.aspx', {PageSize:15},
function (data) {
$('#OutputDiv').html(data);
}
);
Using getJSON()
• $.getJSON(url,data,callback) can retrieve data from a
server:
$.getJSON('CustomerJson.aspx',{id:1},
function (data) {
alert(data.FirstName + ' ' +
data.LastName);
});
Important AJAX settings to note:
• url - The target of the request.
• type - The type of HTTP request either: "GET" (Default) or "POST".
• async - Set asyncronous to TRUE if you want it to load in background and this will allow you to
run mutiple AJAX requests at the same time. If you set to FALSE the request will run and then wait
for the result before preceeding with the rest of you code.
• data - Specify data you wish to pass with the AJAX call in "{param1: 'value1'}" format.
• dataType - Specify the type of data that is returned: "xml/html/script/json/jsonp".
• success - The function that is fired when the AJAX call has completed successfully.
• error - The function that is fired when the AJAX call encountered errors.
• jsonp - Allows you to specify a callback function when making cross domain AJAX calls.
• timeout - You can also set a timeout on the AJAX call in milliseconds.
Using the ajax() Function
The ajax() function is configured by assigning
values to JSON properties:
$.ajax({
url: '../CustomerService.svc/InsertCustomer',
data: customer,
dataType: 'json',
success: function (data, status, xhr) {
alert("Insert status: " + data.d.Status + '\n'
+
data.d.Message);
},
error: function (xhr, status, error) {
alert('Error occurred: ' + status);
}
});
Extending the Library
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
//pass jQuery to the function, So that we will able to use any valid Javascript variable name ,to replace
"$" SIGN.
})(jQuery);
jQuery UI
Interactions
Draggable
Droppable
Resizable
Selectable
Sortable
Widgets
Accordion ,Autocomplete, Datepicker, Dialog, Menu,
Progressbar,Slider,Tabs,Tooltip
Effects
Effects ,Add class,color animation,switch class,toggle
class…Etc
Themable widgets
Date picker
$('#date').datepicker();
<input type="text" name="date" id="date" />
Tabs
$(function() {
$( "#tabs" ).tabs();
});
Selectable
$(function() {
$( "#selectable" ).selectable();
});
Themable widgets
• Autocomplete
var availableTags = [ "ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++" ];
$( "#tags" ).autocomplete({ source: availableTags });
<input type="text" id="tags" />
Dialog
$(function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
});
Summary
jQuery is a fast, small, and feature-rich JavaScript library.It makes things like
HTML document traversal and manipulation, event handling, animation, and Ajax
much simpler with an easy-to-use API that works across a multitude of browsers.
With a combination of versatility and extensibility, jQuery has changed the way
that millions of people write JavaScript.
jQuery UI is a curated set of user interface interactions, effects, widgets, and
themes built on top of the jQuery JavaScript Library. Whether you're building
highly interactive web applications or you just need to add a date picker to a form
control, jQuery UI is the perfect choice.
References
http://jquery.com/
http://jqueryui.com/
http://www.sencha.com/products/extjs
http://jquerytools.org/
http://visualjquery.com/
http://kprsekhar.blogspot.in
Download