Top Banner
RAJASEKHAR K
63

Rajasekhar K

Jan 06, 2016

Download

Documents

dara

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?. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Rajasekhar K

RAJASEKHAR K

Page 2: Rajasekhar K

Whats the problem with JavaScript?

Page 3: Rajasekhar K

JavaScript is a weakly typed, classless,

prototype based OO language, that can

also be used outside the browser. It is not

a browser DOM.

Page 4: Rajasekhar K

This session is about improving your Quality of Life !

Page 5: Rajasekhar K

What is jQuery?

Page 6: Rajasekhar K

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

Page 7: Rajasekhar K

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?

Page 8: Rajasekhar K

Introduction to jQuery

Page 9: Rajasekhar K

$(“#firstName”).text(“Joe Black”);

$(“button”).click(function() {alert

“Clicked”;});

$(“.content”).hide();

$(“#main”).load(“content.htm”);

$(“<div/

>”).html(“Loading…”).appendTo(“#content”);

$(“#firstName”).text(“Joe Black”);

$(“button”).click(function() {alert

“Clicked”;});

$(“.content”).hide();

$(“#main”).load(“content.htm”);

$(“<div/

>”).html(“Loading…”).appendTo(“#content”);

A Quality of Life by jQuery

Very compact and fluent programming model

Page 10: Rajasekhar K

<script src=“jquery.js”/><script src=“jquery.js”/>

Reference it in your markup

You can also reference it from Google<script src=“http://ajax.googleapis.com/

ajax/libs/jquery/1.2.6/jquery.min.js”>

</script>

<script src=“http://ajax.googleapis.com/

ajax/libs/jquery/1.2.6/jquery.min.js”>

</script>

Page 11: Rajasekhar K

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

Page 12: Rajasekhar K

The Magic $() function

Fired when the document is ready for programming.

full syntax:

Simply :

$(document).ready(function(){…});$(document).ready(function(){…});

$(function(){…});$(function(){…});

Page 13: Rajasekhar K

var foo = jQuery.noConflict();

// now foo() is the jQuery main function

foo(“div”).hide();

var foo = jQuery.noConflict();

// now foo() is the jQuery main function

foo(“div”).hide();

Avoid $() conflict with other frameworks

$.noConflict();jQuery(document).ready(function(){  jQuery("button").click(function(){    jQuery("p").text("jQuery is still working!");  });});

$.noConflict();jQuery(document).ready(function(){  jQuery("button").click(function(){    jQuery("p").text("jQuery is still working!");  });});

Page 14: Rajasekhar K

jQuery Selectors

Page 15: Rajasekhar K

$(“*”) // find everything

$(“*”) // find everything

All Selector

Selectors return a pseudo-array of jQuery elements

$(document).ready(function(){ $("button").click(function(){ $("*").hide(); });});

$(document).ready(function(){ $("button").click(function(){ $("*").hide(); });});

Page 16: Rajasekhar K

$(“div”)

// <div>Hello jQuery</div>

$(“div”)

// <div>Hello jQuery</div>

Basic Selectors

Yes, jQuery implements CSS Selectors!

$(“#usr”)

// <span id=“usr”>John</span>

$(“#usr”)

// <span id=“usr”>John</span>

$(“.menu”)

// <ul class=“menu”>Home</ul>

$(“.menu”)

// <ul class=“menu”>Home</ul>

By Tag:

By ID:

By Class:

Page 17: Rajasekhar K

$(“div.main”) // tag and class

$(“table#data”) // tag and id

$(“div.main”) // tag and class

$(“table#data”) // tag and id

More Precise Selectors

Combination of Selectors

// find by id + by class

$(“#content, .menu”)

// multiple combination

$(“h1, h2, h3, div.content”)

// find by id + by class

$(“#content, .menu”)

// multiple combination

$(“h1, h2, h3, div.content”)

Page 18: Rajasekhar K

$(“table td”) // descendants

$(“tr > td”) // children

$(“label + input”) // next

$(“#content ~ div”) // siblings

$(“table td”) // descendants

$(“tr > td”) // children

$(“label + input”) // next

$(“#content ~ div”) // siblings

Hierarchy Selectors

$("ul.topnav > li").css("border", "3px double red"); $("ul.topnav > li").css("border", "3px double red");

Page 19: Rajasekhar K

$(“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

$(“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

Selection Index Filters

$( "td:gt(4)" ).css( "backgroundColor", "yellow" );

$('li').filter(':even').css('background-color', 'red');

$( "td:gt(4)" ).css( "backgroundColor", "yellow" );

$('li').filter(':even').css('background-color', 'red');

Page 20: Rajasekhar K

$(“div[id]”) // has attribute

$(“div[dir=‘rtl’]”) // equals to

$(“div[id^=‘main’]”) // starts with

$(“div[id$=‘name’]”) // ends with

$(“a[href*=‘msdn’]”) // contains

$(“div[id]”) // has attribute

$(“div[dir=‘rtl’]”) // equals to

$(“div[id^=‘main’]”) // starts with

$(“div[id$=‘name’]”) // ends with

$(“a[href*=‘msdn’]”) // contains

Attribute Filters

$('input[name*=“JavaScript"]').val(‘jQuery!'); $('input[name*=“JavaScript"]').val(‘jQuery!');

Page 21: Rajasekhar K

$(“input:checkbox”) // checkboxes

$(“input:radio”) // radio buttons

$(“:button”) // buttons

$(“:text”) // text inputs

$(“input:checkbox”) // checkboxes

$(“input:radio”) // radio buttons

$(“:button”) // buttons

$(“:text”) // text inputs

Forms Selectors

Page 22: Rajasekhar K

$(“input:checked”) // checked

$(“input:selected”) // selected

$(“input:enabled”) // enabled

$(“input:disabled”) // disabled

$(“input:checked”) // checked

$(“input:selected”) // selected

$(“input:enabled”) // enabled

$(“input:disabled”) // disabled

Forms Filters

<input type="checkbox" name="newsletter" value="Hourly" checked="checked"> <input type="checkbox" name="newsletter" value="Hourly" checked="checked">

Page 23: Rajasekhar K

$(“select[name=‘ddl’] option:selected”).val()

$(“select[name=‘ddl’] option:selected”).val()

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=“cities”>

<option value=“1”>Tel-Aviv</option>

<option value=“2” selected=“selected”>Yavne</option>

<option value=“3”>Raanana</option>

</select>

Page 24: Rajasekhar K

Document Traversal

Page 25: Rajasekhar K

.next(expr) // next sibling

.prev(expr) // previous sibling

.siblings(expr) // siblings

.children(expr) // children

.parent(expr) // parent

.next(expr) // next sibling

.prev(expr) // previous sibling

.siblings(expr) // siblings

.children(expr) // children

.parent(expr) // parent

Traversing HTML

$("p").next(".selected").css("background", "yellow");

$("p").next(".selected").css("background", "yellow");

Page 26: Rajasekhar K

$(“table td”).each(function() {if ($(this).is(“:first-

child”)) {$

(this).addClass(“firstCol”);}

});

$(“table td”).each(function() {if ($(this).is(“:first-

child”)) {$

(this).addClass(“firstCol”);}

});

Check for expression

Page 27: Rajasekhar K

HTML Manipulation

Page 28: Rajasekhar K

$(“img”).attr({“src” :

“/images/smile.jpg”,“alt” : “Smile”,“width” : 10,“height” : 10

});

$(“img”).attr({“src” :

“/images/smile.jpg”,“alt” : “Smile”,“width” : 10,“height” : 10

});

Setting multiple attributes

Page 29: Rajasekhar K

// get style$(“div”).css(“background-color”);

// get style$(“div”).css(“background-color”);

CSS Manipulations

// set style

$(“div”).css(“float”, “left”);// set style

$(“div”).css(“float”, “left”);

// set multiple style properties$(“div”).css({“color”:”blue”,

“padding”: “1em” “margin-right”: “0”, marginLeft: “10px”});

// set multiple style properties$(“div”).css({“color”:”blue”,

“padding”: “1em” “margin-right”: “0”, marginLeft: “10px”});

Page 30: Rajasekhar K

Events

Page 31: Rajasekhar K

Handling Events using JavaScript

Question:

What type of JavaScript code do you write to handle a button click event ?

Answer :

It depends on browser...!!!

Page 32: Rajasekhar K

Event Attachment Techniques

• Most Browsers:

• Internet Explorer (IE8 and Opera)

myButton.addEventListener('click',function(){ },false); myButton.addEventListener('click',function(){ },false);

myButton.attachEvent('onClick',function(){ }); myButton.attachEvent('onClick',function(){ });

Page 33: Rajasekhar K

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

Page 34: Rajasekhar K

$(“#myID”).click(function(){

alert(‘The element ID Clicked’);

});

// execute always$(“div”).bind(“click”, fn);

// execute only once$(“div”).one(“click”, fn);

$(“#myID”).click(function(){

alert(‘The element ID Clicked’);

});

// execute always$(“div”).bind(“click”, fn);

// execute only once$(“div”).one(“click”, fn);

Attach Event

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)

Page 35: Rajasekhar K

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");

});

});

$(document).ready(function(){

$("div").delegate("p","click",function(){

$("p").css("background-color","pink");

});

});

Page 36: Rajasekhar K

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');

});

});

$(document).ready(function () {

$(document).on("click","div", function(){ $('<div>Dynamic Div</div>').appendTo('body');

});

});

Page 37: Rajasekhar K

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'); });

$('#target').hover(function() { $(this).css('background-color', '#00FF99'); }, function() { $(this).css('background-color', '#FFFFFF'); });

Page 38: Rajasekhar K

Alternate Hover Example• Another option is

• Fires the same handler for mouseenter and mouseleave events

• Used with jQuery's toggle methods:

This code will toggle the class applied to a paragraph element

$(selector).hover(handlerInOut); $(selector).hover(handlerInOut);

$('p').hover(function() { $(this).toggleClass('over'); });

$('p').hover(function() { $(this).toggleClass('over'); });

Page 39: Rajasekhar K

Effects

Page 40: Rajasekhar K

$(“div”).show();

// hide fast, fast=200ms$(“div”).hide(“fast”);

// hide or show in 100ms $(“div”).toggle(100);

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

$(“div”).show();

// hide fast, fast=200ms$(“div”).hide(“fast”);

// hide or show in 100ms $(“div”).toggle(100);

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

Showing or Hiding Element

Page 41: Rajasekhar K

$(“div”).animate({width: “90%”},100)

.animate({opacity: 0.5},200)

.animate({borderWidth: “5px”});

$(“div”).animate({width: “90%”},100)

.animate({opacity: 0.5},200)

.animate({borderWidth: “5px”});

Chaining Animation

By default animations are queued and than performed one by one

Page 42: Rajasekhar K

AJAX with jQuery

Page 43: Rajasekhar K

$.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.

Page 44: Rajasekhar K

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

Page 45: Rajasekhar K

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');

});

});

$(document).ready(function(){

$('#HelpButton').click(function(){

$

('#MyDiv').load('HelpDetails.html');

});

});

Page 46: Rajasekhar K

Using get()

• $.get(url,data,callback,datatype) can retrieve data from a server:

$.get('HelpDetails.html', function (data) { $('#OutputDiv').html(data);});

$.get('HelpDetails.html', function (data) { $('#OutputDiv').html(data);});

Page 47: Rajasekhar K

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); });

$.post('GetCustomers.aspx', {PageSize:15}, function (data) { $('#OutputDiv').html(data); });

Page 48: Rajasekhar K

Using getJSON()

• $.getJSON(url,data,callback) can retrieve data from a server:

$.getJSON('CustomerJson.aspx',{id:1}, function (data) { alert(data.FirstName + ' ' + data.LastName);});

$.getJSON('CustomerJson.aspx',{id:1}, function (data) { alert(data.FirstName + ' ' + data.LastName);});

Page 49: Rajasekhar K

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.

Page 50: Rajasekhar K

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); } });

$.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); } });

Page 51: Rajasekhar K

Extending the Library

Page 52: Rajasekhar K

(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);

(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);

Page 53: Rajasekhar K
Page 54: Rajasekhar K

jQuery UIInteractions

Widgets

Effects

DraggableDroppableResizableSelectableSortable

Accordion ,Autocomplete, Datepicker, Dialog, Menu, Progressbar,Slider,Tabs,Tooltip

Effects ,Add class,color animation,switch class,toggle class…Etc

Page 55: Rajasekhar K

Themable widgets

Date picker

$('#date').datepicker();

<input type="text" name="date" id="date" />

$('#date').datepicker();

<input type="text" name="date" id="date" />

Page 56: Rajasekhar K

Tabs

$(function() { $( "#tabs" ).tabs();});

$(function() { $( "#tabs" ).tabs();});

Page 57: Rajasekhar K

Selectable

$(function() { $( "#selectable" ).selectable();});

$(function() { $( "#selectable" ).selectable();});

Page 58: Rajasekhar K

Themable widgets

• Autocomplete

var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++" ]; $( "#tags" ).autocomplete({ source: availableTags }); <input type="text" id="tags" />

var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++" ]; $( "#tags" ).autocomplete({ source: availableTags }); <input type="text" id="tags" />

Page 59: Rajasekhar K

Dialog$(function() { $( "#dialog-message" ).dialog({

modal: true,buttons: { Ok: function() { $( this ).dialog( "close" );}

} });});

$(function() { $( "#dialog-message" ).dialog({

modal: true,buttons: { Ok: function() { $( this ).dialog( "close" );}

} });});

Page 60: Rajasekhar K

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.

Summary

Page 61: Rajasekhar K

References

http://jquery.com/

http://jqueryui.com/

http://www.sencha.com/products/extjs

http://jquerytools.org/

http://visualjquery.com/

http://kprsekhar.blogspot.in

Page 62: Rajasekhar K
Page 63: Rajasekhar K