Download presentation
Presentation is loading. Please wait.
Published byClarence Allen Modified over 8 years ago
1
RAJASEKHAR K
2
Whats the problem with JavaScript?
3
JavaScript is a weakly typed, classless, prototype based OO language, that can also be used outside the browser. It is not a browser DOM.
4
This session is about improving your Quality of Life !
5
What is jQuery?
6
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
7
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?
8
Introduction to jQuery
9
$(“#firstName”).text(“Joe Black”); $(“button”).click(function() {alert “Clicked”;}); $(“.content”).hide(); $(“#main”).load(“content.htm”); $(“ ”).html(“Loading…”).appendTo(“#content”); $(“#firstName”).text(“Joe Black”); $(“button”).click(function() {alert “Clicked”;}); $(“.content”).hide(); $(“#main”).load(“content.htm”); $(“ ”).html(“Loading…”).appendTo(“#content”); A Quality of Life by jQuery Very compact and fluent programming model
10
Reference it in your markup You can also reference it from Google
11
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"> if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='Scripts/jquery.1.9.0.min.js' type='text/javascript'%3E%3C/script%3E")); } Not using selectors efficiently Using jQuery selectors repeatedly Not checking while using various plugins
12
The Magic $() function Fired when the document is ready for programming. full syntax: Simply : $(document).ready(function(){…}); $(function(){…});
13
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!"); }); });
14
jQuery Selectors
15
$(“*”) // 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(); });
16
$(“div”) // Hello jQuery $(“div”) // Hello jQuery Basic Selectors Yes, jQuery implements CSS Selectors! $(“#usr”) // John $(“#usr”) // John $(“.menu”) // Home $(“.menu”) // Home By Tag: By ID: By Class:
17
$(“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”)
18
$(“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");
19
$(“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');
20
$(“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!');
21
$(“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
22
$(“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
23
$(“select[name=‘ddl’] option:selected”).val() Find Dropdown Selected Item Tel-Aviv Yavne Raanana Tel-Aviv Yavne Raanana
24
Document Traversal
25
.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");
26
$(“table td”).each(function() { if ($(this).is(“:first-child”)) { $(this).addClass(“firstCol”); } }); Check for expression
27
HTML Manipulation
28
$(“img”).attr({ “src” : “/images/smile.jpg”, “alt” : “Smile”, “width” : 10, “height” : 10 }); Setting multiple attributes
29
// get style $(“div”).css(“background-color”); CSS Manipulations // set style $(“div”).css(“float”, “left”); // set multiple style properties $(“div”).css({“color”:”blue”, “padding”: “1em” “margin-right”: “0”, marginLeft: “10px”});
30
Events
31
Handling Events using JavaScript Question: What type of JavaScript code do you write to handle a button click event ? Answer : It depends on browser...!!!
32
Event Attachment Techniques Most Browsers: Internet Explorer (IE8 and Opera) myButton.addEventListener('click',function(){ },false); myButton.attachEvent('onClick',function(){ });
33
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
34
$(“# 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)
35
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"); });
36
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(){ $(' Dynamic Div ').appendTo('body'); }); $(document).ready(function () { $(document).on("click","div", function(){ $(' Dynamic Div ').appendTo('body'); });
37
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'); });
38
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); $('p').hover(function() { $(this).toggleClass('over'); }); $('p').hover(function() { $(this).toggleClass('over'); });
39
Effects
40
$(“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
41
$(“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
42
AJAX with jQuery
43
$.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.
44
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
45
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'); });
46
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); });
47
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); } );
48
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); });
49
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.
50
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); } });
51
Extending the Library
52
(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);
54
jQuery UI Interactions Widgets Effects Draggable Droppable Resizable Selectable Sortable Accordion,Autocomplete, Datepicker, Dialog, Menu, Progressbar,Slider,Tabs,Tooltip Effects,Add class,color animation,switch class,toggle class…Etc
55
Themable widgets Date picker $('#date').datepicker(); $('#date').datepicker();
56
Tabs $(function() { $( "#tabs" ).tabs(); });
57
Selectable $(function() { $( "#selectable" ).selectable(); });
58
Themable widgets Autocomplete var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++" ]; $( "#tags" ).autocomplete({ source: availableTags }); var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++" ]; $( "#tags" ).autocomplete({ source: availableTags });
59
Dialog $(function() { $( "#dialog-message" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); });
60
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
61
References http://jquery.com/ http://jqueryui.com/ http://www.sencha.com/products/extjs http://jquerytools.org/ http://visualjquery.com/ http://kprsekhar.blogspot.in
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.