1 / 63

Rajasekhar K

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

dara
Download Presentation

Rajasekhar K

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  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. A Quality of Life by jQuery Very compact and fluent programming model $(“#firstName”).text(“Joe Black”); $(“button”).click(function() {alert “Clicked”;}); $(“.content”).hide(); $(“#main”).load(“content.htm”); $(“<div/>”).html(“Loading…”).appendTo(“#content”);

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

  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"></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

  12. The Magic $() function Fired when the document is ready for programming.fullsyntax: Simply : • $(document).ready(function(){…}); • $(function(){…});

  13. 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!");  });});

  14. jQuery Selectors

  15. All Selector • $(“*”) // find everything Selectors return a pseudo-array of jQuery elements $(document).ready(function(){ $("button").click(function(){ $("*").hide(); }); });

  16. 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!

  17. 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”)

  18. Hierarchy Selectors • $(“table td”) // descendants • $(“tr > td”) // children • $(“label + input”) // next • $(“#content ~ div”) // siblings • $("ul.topnav > li").css("border", "3px double red");

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

  20. 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!');

  21. Forms Selectors • $(“input:checkbox”) // checkboxes • $(“input:radio”) // radio buttons • $(“:button”) // buttons • $(“:text”) // text inputs

  22. Forms Filters • $(“input:checked”) // checked • $(“input:selected”) // selected • $(“input:enabled”) // enabled • $(“input:disabled”) // disabled <input type="checkbox" name="newsletter" value="Hourly" checked="checked">

  23. 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()

  24. Document Traversal

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

  26. Check for expression • $(“table td”).each(function() { if ($(this).is(“:first-child”)) { $(this).addClass(“firstCol”); }});

  27. HTML Manipulation

  28. Setting multiple attributes • $(“img”).attr({ “src” : “/images/smile.jpg”, “alt” : “Smile”, “width” : 10, “height” : 10});

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

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

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

  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(){ $('<div>Dynamic Div</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'); });

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

  39. Effects

  40. 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”);

  41. Chaining Animation By default animations are queued and than performed one by one • $(“div”).animate({width: “90%”},100) .animate({opacity: 0.5},200) .animate({borderWidth: “5px”});

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

  46. Using get() • $.get(url,data,callback,datatype) can retrieve data from a server: • $.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); • } • );

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

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

More Related