• 1. The magic of jQuery Vlad Azarkhin Senior Architect & Technologist
  • 2. What’s the problem with JavaScript?
  • 3. JavaScript was a initially introduced in Netscape 2.0B3 in Dec 1995, a.k.a. Mocha, LiveScript, Jscript, however, it’s official name is ECMAScript
  • 4. JavaScript is a C-family, world’s worst named, extremely powerful language (not a script), totally unrelated to Java
  • 5. JavaScript is a weakly typed, classless, prototype based OO language, that can also be used outside the browser. It is not a browser DOM.
  • 6. The world’s most misunderstood programming language. (Douglas Crockford)
  • 7. Browser DOM really sucks, and this is where jQuery comes to rescue.
  • 8. This session is about improving your Quality of Life !
  • 9. Introduction to jQuery
  • 10. $(“#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
  • 11. What is jQuery?
  • 12. jQuery is a lightweight, open-source JavaScript library that simplifies interaction between HTML and JavaScript
  • 13. It was and still being developed by John Resig from Mozilla and was first announced in January 2006
  • 14. It has a great community, great documentation, tons of plugins, and it was recently adopted by Microsoft (how about intellisense in VS?)
  • 15. The current version is 1.3.2 (as of July 2009)
  • 16. Getting Started
  • 17. Download the latest version from http://jquery.com
  • 18. To enable itellisense in VS 2008 SP1 install the –vsdoc hotfix: VS90SP1-KB958502-x86.exe
  • 19. Copy the jquery.js and the jquery-vsdoc.js into your application folder
  • 20. No need to reference the –vsdoc.jsYou can also reference it from Google
  • 23. jQuery Core Concepts
  • 24. Create HTML elements on the flyvar el = $(“
    ”)The Magic $() function
  • 25. Manipulate existing DOM elements$(window).width()The Magic $() function
  • 26. Selects document elements (more in a moment…)$(“div”).hide(); $(“div”, $(“p”)).hide();The Magic $() function
  • 27. $(document).ready(function(){…});Fired when the document is ready for programming. Better use the full syntax: $(function(){…});The Magic $() function
  • 28. It may be used in case of conflict with other frameworks.jQuery(“div”);The full name of $() function is
  • 29. jQuery uses closures for isolation(function(){ var jQuery=window.jQuery=window.$=function(){ // … }; })();The library is designed to be isolated
  • 30. var foo = jQuery.noConflict(); // now foo() is the jQuery main function foo(“div”).hide();Avoid $() conflict with other frameworks // remove the conflicting $ and jQuery var foo = jQuery.noConflict(true);
  • 31. $(“div”).hide() $(“”).appendTo(“body”) $(“:button”).click()jQuery’s programming philosophy is: GET >> ACT
  • 32. $(“div”).show() .addClass(“main”) .html(“Hello jQuery”);Almost every function returns jQuery, which provides a fluent programming interface and chainability:
  • 33. Get > ActChainabilityThe $() functionThree Major Concepts of jQuery
  • 34. jQuery Selectors
  • 35. $(“*”) // find everythingAll Selector Selectors return a pseudo-array of jQuery elements
  • 36. $(“div”) //
    Hello jQuery
    Basic Selectors Yes, jQuery implements CSS Selectors!$(“#usr”) // John$(“.menu”) //
      Home
    By Tag:By ID:By Class:
  • 37. $(“div.main”) // tag and class $(“table#data”) // tag and idMore Precise Selectors
  • 38. // find by id + by class $(“#content, .menu”) // multiple combination $(“h1, h2, h3, div.content”)Combination of Selectors
  • 39. $(“table td”) // descendants $(“tr > td”) // children $(“label + input”) // next $(“#content ~ div”) // siblingsHierarchy Selectors
  • 40. $(“tr:first”) // first element $(“tr:last”) // last element $(“tr:lt(2)”) // index less than $(“tr:gt(2)”) // index gr. than $(“tr:eq(2)”) // index equalsSelection Index Filters
  • 41. $(“div:visible”) // if visible $(“div:hidden”) // if notVisibility Filters
  • 42. $(“div[id]”) // has attribute $(“div[dir=‘rtl’]”) // equals to $(“div[id^=‘main’]”) // starts with $(“div[id$=‘name’]”) // ends with $(“a[href*=‘msdn’]”) // containsAttribute Filters
  • 43. $(“input:checkbox”) // checkboxes $(“input:radio”) // radio buttons $(“:button”) // buttons $(“:text”) // text inputsForms Selectors
  • 44. $(“input:checked”) // checked $(“input:selected”) // selected $(“input:enabled”) // enabled $(“input:disabled”) // disabledForms Filters
  • 45. $(“select[name=‘ddl’] option:selected”).val()Find Dropdown Selected Item
  • 46. SELECTORS DEMO
  • 47. (本页无文本内容)
  • 48. Document Traversal
  • 49. $(“div”).lengthReturns number of selected elements. It is the best way to check selector.A Selector returns a pseudo array of jQuery objects
  • 50. $(“div”).get(2) or $(“div”)[2]Returns a 2nd DOM element of the selectionGetting a specific DOM element
  • 51. $(“div”).eq(2)Returns a 2nd jQuery element of the selectionGetting a specific jQuery element
  • 52. var sum = 0; $(“div.number”).each( function(){ sum += (+this.innerHTML); });this – is a current DOM elementeach(fn) traverses every selected element calling fn()
  • 53. $(“table tr”).each( function(i){ if (i % 2) $(this).addClass(“odd”); });$(this) – convert DOM to jQuery i - index of the current elementeach(fn) also passes an indexer
  • 54. .next(expr) // next sibling .prev(expr) // previous sibling .siblings(expr) // siblings .children(expr) // children .parent(expr) // parentTraversing HTML
  • 55. $(“table td”).each(function() { if ($(this).is(“:first-child”)) { $(this).addClass(“firstCol”); } }); Check for expression
  • 56. // select paragraph and then find // elements with class ‘header’ inside $(“p”).find(“.header”).show(); // equivalent to: $(“.header”, $(“p”)).show();Find in selected
  • 57. $(“
  • ”) // li .find(“span”) // span .html(“About Us”) // span .andSelf() // span, li .addClass(“menu”) // span,li .end() // span .end() // li .appendTo(“ul.main-menu”);Advanced Chaining
  • 58. $(“div”) .slice(2, 5) .not(“.green”) .addClass(“middle”);Get Part of Selected Result
  • 59. HTML Manipulation
  • 60. $(“p”).html(“
    Hello $!
    ”); // escape the content of div.b $(“div.a”).text($(“div.b”).html());Getting and Setting Inner Content
  • 61. // get the value of the checked checkbox $(“input:checkbox:checked”).val();Getting and Setting Values // set the value of the textbox $(“:text[name=‘txt’]”).val(“Hello”);// select or check lists or checkboxes $(“#lst”).val([“NY”,”IL”,”NS”]);
  • 62. Handling CSS Classes // add and remove class $(“p”).removeClass(“blue”).addClass(“red”);// add if absent, remove otherwise $(“div”).toggleClass(“main”);// test for class existance if ($(“div”).hasClass(“main”)) { //… }
  • 63. // select > append to the end $(“h1”).append(“
  • Hello $!
  • ”); // select > append to the beginning $(“ul”).prepend(“
  • Hello $!
  • ”);Inserting new Elements // create > append/prepend to selector $(“
  • ”).html(“9”).appendTo(“ul”); $(“
  • ”).html(“1”).prependTo(“ul”);
  • 64. // select > replace $(“h1”).replaceWith(“
    Hello
    ”);Replacing Elements // create > replace selection $(“
    Hello
    ”).replaceAll(“h1”);
  • 65. $(“h3”).each(function(){ $(this).replaceWith(“
    ” + $(this).html() + ”
    ”); });Replacing Elements while keeping the content
  • 66. // remove all children $(“#mainContent”).empty();Deleting Elements // remove selection $(“span.names”).remove();// change position $(“p”).remove(“:not(.red)”) .appendTo(“#main”);
  • 67. $(“a”).attr(“href”,”home.htm”); // Handling attributes // set the same as the first one $(“button:gt(0)”).attr(“disabled”, $(“button:eq(0)”).attr(“disabled));// remove attribute - enable $(“button”).removeAttr(“disabled”)
  • 68. $(“img”).attr({ “src” : “/images/smile.jpg”, “alt” : “Smile”, “width” : 10, “height” : 10 });Setting multiple attributes
  • 69. // 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”});
  • 70. // get window height var winHeight = $(window).height(); // set element height $(“#main”).height(winHeight); //.width() – element //.innerWidth() – .width() + padding //.outerWidth() – .innerWidth() + border //.outerWidth(true) – including marginDimensions The default unit is Pixel (px)
  • 71. // from the document $(“div”).offset().top; // from the parent element $(“div”).position().left; // scrolling position $(window).scrollTop(); Positioning
  • 72. Events
  • 73. $(document).ready(function(){ //… });When the DOM is ready… Fires when the document is ready for programming. Uses advanced listeners for detecting. window.onload() is a fallback.
  • 74. // 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)
  • 75. jQuery.Event object
  • 76. $(“div”).unbind(“click”, fn);Detaching Events (Unique ID added to every attached function)
  • 77. $(“div”).trigger(“click”);Events Triggering Triggers browser’s event action as well. Can trigger custom events. Triggered events bubble up.
  • 78. // attach / trigger elem.blur(fn) / elem.blur() elem.focus(fn) / elem.focus() elem.click(fn) / elem.click() elem.change(fn) / elem.change()Events Helpers And many others…
  • 79. // use different triggering function $(“div”).triggerHandler(“click”);Preventing Browser Default Action // prevent default action in handler function clickHandler(e) { e.preventDefault(); }// or just return false function clickHandler(e) {return false;}
  • 80. // stop bubbling, keep other handler function clickHandler(e) { e.stopPropagation(); }Preventing Bubbling // stop bubbling and other handlers function clickHandler(e) { e.stopImmediatePropagation(); }// or just return false function clickHandler(e) {return false;}
  • 81. // attach live event (“div”).live(“click”, fn); // detach live event (“div”).die(“click”, fn);Live Events Currently supported events: click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup
  • 82. EVENTS DEMO
  • 83. Effects
  • 84. // just show $(“div”).show(); // reveal slowly, slow=600ms $(“div”).show(“slow”); // hide fast, fast=200ms $(“div”).hide(“fast”); // hide or show in 100ms $(“div”).toggle(100);Showing or Hiding Element
  • 85. $(“div”).slideUp(); $(“div”).slideDown(“fast”); $(“div”).slideToggle(1000);Sliding Elements
  • 86. $(“div”).fadeIn(“fast”); $(“div”).fadeOut(“normal”); // fade to a custom opacity $(“div”).fadeTo (“fast”, 0.5);Fading Elements Fading === changing opacity
  • 87. $(“div”).hide(“slow”, function() { alert(“The DIV is hidden”); }); $(“div”).show(“fast”, function() { $(this).html(“Hello jQuery”); }); // this is a current DOM element Detecting animation completion Every effect function has a (speed, callback) overload
  • 88. // .animate(options, duration) $(“div”).animate({ width: “90%”, opacity: 0.5, borderWidth: “5px” }, 1000);Custom Animation
  • 89. $(“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
  • 90. $(“div”) .animate({width: “90%”}, {queue:false, duration:1000}) .animate({opacity : 0.5}); Controlling Animations Sync The first animation will be performed immediately without queuing
  • 91. EFFECTS DEMO
  • 92. AJAX with jQuery
  • 93. $(“div”).load(“content.htm”); // passing parameters $(“#content”).load(“getcontent.aspx”, {“id”:”33”, “type”:”main”});Loading content
  • 94. $.get(“test.aspx”, {id:1}, function(data){alert(data);}); $.post(“test.aspx”, {id:1}, function(data){alert(data);});Sending GET/POST requests
  • 95. $.getJSON(“users.aspx”, {id:1}, function(users) { alert(users[0].name); });Retrieving JSON Data
  • 96. $.getScript(“script.js”, function() { doSomeFunction(); });Retrieving JS Files
  • 97. AJAX DEMO
  • 98. Extending the Library
  • 99. // definition jQuery.fn.printLine = function(s) { return jQuery(this).each(function() { this.append(“
    ”+ s +“
    ”); }); }; // usage $(“#log”).printLine(“Hello”);Adding Methods Do not use $ in the method (at least not until next slide)
  • 100. (function ($) { jQuery.fn.printLine = function(s) { return $(this).each(function() { this.append(“
    ”+ s +“
    ”); }); }; })(jQuery);Closure to solve the $ issue
  • 101. $.expr[‘:’].test = function(o, i, m, s) { // o – current object in the selection // i – loop index in the stack // m – meta data about your selector // s – stack of all the elements // return true to include the element // return false to exclude the element };Custom Selectors
  • 102. LIBRARY EXTENSION DEMO
  • 103. More Functionality on every aspect URL parameters parser Browser and features detection Data Cache Utilities Helper functions Various Plug-ins More things to explore
  • 104. jQuery web-site: http://jquery.com jQuery API: http://api.jquery.com Many many blogs jQuery in Action book: Where to go next
  • 105. Blog: http://blogs.microsoft.co.il/blogs/linqed Email: vlad@netwise.co.il Contact me Thank YOU!