rajasekhar k. whats the problem with javascript?

63
RAJASEKHAR K

Upload: clarence-allen

Post on 23-Dec-2015

237 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: RAJASEKHAR K. Whats the problem with JavaScript?

RAJASEKHAR K

Page 2: RAJASEKHAR K. Whats the problem with JavaScript?

Whats the problem with JavaScript?

Page 3: 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.

Page 4: RAJASEKHAR K. Whats the problem with JavaScript?

This session is about improving your Quality of Life !

Page 5: RAJASEKHAR K. Whats the problem with JavaScript?

What is jQuery?

Page 6: RAJASEKHAR K. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

Introduction to jQuery

Page 9: RAJASEKHAR K. Whats the problem with JavaScript?

$(“#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. Whats the problem with JavaScript?

<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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

jQuery Selectors

Page 15: RAJASEKHAR K. Whats the problem with JavaScript?

$(“*”) // 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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

Document Traversal

Page 25: RAJASEKHAR K. Whats the problem with JavaScript?

.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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

HTML Manipulation

Page 28: RAJASEKHAR K. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

// 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. Whats the problem with JavaScript?

Events

Page 31: RAJASEKHAR K. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

$(“#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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

Effects

Page 40: RAJASEKHAR K. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

$(“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. Whats the problem with JavaScript?

AJAX with jQuery

Page 43: RAJASEKHAR K. Whats the problem with JavaScript?

$.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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

Extending the Library

Page 52: RAJASEKHAR K. Whats the problem with JavaScript?

(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. Whats the problem with JavaScript?
Page 54: RAJASEKHAR K. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

Tabs

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

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

Page 57: RAJASEKHAR K. Whats the problem with JavaScript?

Selectable

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

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

Page 58: RAJASEKHAR K. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?

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. Whats the problem with JavaScript?
Page 63: RAJASEKHAR K. Whats the problem with JavaScript?