1 / 80

To jQuery or to Client Library, that’s the question!

To jQuery or to Client Library, that’s the question!. Gill Cleeren. Microsoft Regional Director – Silverlight MVP. Ordina Belgium. Glad to meet you. Gill Cleeren Microsoft Regional Director MVP Silverlight .NET Architect @Ordina ( www.ordina.be )

ziazan
Download Presentation

To jQuery or to Client Library, that’s the question!

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. To jQuery or to Client Library, that’s the question! Gill Cleeren Microsoft Regional Director – Silverlight MVP Ordina Belgium

  2. Glad to meet you... • Gill Cleeren • Microsoft Regional Director • MVP Silverlight • .NET Architect @Ordina (www.ordina.be) • Speaker (TechDays, DevDays, NDC Norway, Spring Conference UK, SQL Server Saturday Switzerland...) • Visug user group lead (www.visug.be) • Author (Silverlight 4 Data and services cookbook) • www.snowball.be - gill@snowball.be- @gillcleeren

  3. What we’ll be looking at... • Part 1: Current state of scripting options for the ASP.NET developer • Where are we now? • Cool features of ASP.NET AJAX • Cool features of the ASP.NET AJAX toolkit • Part 2 : jQuery • Why jQuery? • jQuery fundamentals • Creating and manipulating elements • Events • Animations and effects • Talking to the server using ajax calls • jQuery UI • Templating, data link and globalization

  4. Part 1 Current state of scripting options for the ASP.NET developer

  5. Current state of scripting options for the ASP.NET developer Today – 1 year ago (about ): Microsoft announced it ceased further development in AJAX Client Library

  6. Current state of scripting options for the ASP.NET developer Instead, Microsoft announcedto invest in building jQueryplugins. Up first is porting existingfunctionality to jQuery.

  7. Current state of scripting options for the ASP.NET developer Conclusion: don’t invest any new development time in client library!Don’t panic if you have, there’s still support for the current version!

  8. Current state of scripting options for the ASP.NET developer • There is continued investment in • ASP.NET AJAX • ASP.NET AJAX Control Toolkit • Let’s look at a few new and nice features of these!

  9. ASP.NET AJAX

  10. ASP.NET AJAX: The ScriptManager • Exists since ASP.NET 2.0 AJAX • Enhanced over time with 3.5 and 4.0 • Used for managing/downloading scripts • Microsoft • Own scripts • Cool features of the ScriptManager • Combine Scripts (more in the next slide) • Compress Scripts (more in the next slide) • Cache Scripts with a Far Future header • Use the Microsoft Ajax CDN (ASP.NET 4)

  11. The CompositeScript function • Can be used to combine several scripts • Can be used in combination with jQuery, jQuery UI... • Results in less server calls from the browser  faster • Automatically adds • Far Future Header • Script remains cached for long time, less downloads  faster • Compression of script code (GZIP)

  12. Using a CDN • CDN = ?? • Canadian Dairy Network? • Coin Dealer Newsletter? • Cultural Diversity Network? • CDN = Content delivery Network

  13. Using a CDN • It’s possible to load all ASP.NET Framework scripts and other scripts from the Microsoft CDN • AJAX • Web Forms scripts • AJAX Control Toolkit • jQuery • Probably not for internal apps

  14. Why a CDN? • Local script loading (geo-aware) • Servers located around the world • Bandwidth reduction • No need to pay for script bandwidth, operations • Faster loader times for end-user • Load once, use on multiple sites • Automatically added headers for caching and compression • One year expiration, GZIP compression • Hosts Ajax library scripts such as jQuery and jQuery Validate

  15. Tip: include a fallback • Although a CDN should be always available, include a fallback mechanism to be sure! <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"> </script> <script type="text/javascript"> if (typeof jQuery == 'undefined') {     document.write(unescape("%3Cscript src='/Scripts/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E")); } </script>

  16. demo Using the ScriptManager

  17. ASP.NET AJAX Control Toolkit

  18. AJAX Control Toolkit • Most people know it from the great collection of controls • Server and client-side version available • Client-side can be used with other libraries • Works with 3.5 and 4.0 • Scripts hosted on CDN • Includes a minifier now as well • JS • CSS • Possible to contribute to the project on CodePlex ajaxcontroltoolkit.codeplex.com

  19. Included controls Accordion AlwaysVisibleControl Animation AsyncFileUpload AutoComplete Calendar CascadingDropDown CollapsiblePanel ColorPicker ComboBox ConfirmButton DragPanel DropDown DropShadow PopupControl Rating ReorderList ResizableControl RoundedCorners Seadragon Slider SlideShow Tabs TextBoxWatermark ToggleButton UpdatePanelAnimation ValidatorCallout DynamicPopulate FilteredTextBox HoverMenu HTMLEditor ListSearch MaskedEdit ModalPopup MultiHandleSlider MutuallyExclusive NoBot NumericUpDown PagingBulletedList PasswordStrength

  20. The minifier tool • Can be used to crunch JavaScript or CSS files • Removes whitespace, breaks... • Command-line tool, possible to include as build task ajaxmin test.js -o test.min.js

  21. demo Using the toolkit and the minifier

  22. Part 2 jQuery

  23. Hi, jQuery • jQuery is • Most popular, cross-browser JavaScript library • Focusing on making client-side scripting of HTML simpler • Easy navigating the DOM • Handling events • Working with Ajax • Open-source, released in 2006

  24. Why jQuery? • Many JavaScript frameworks try bending the language out of its natural form • jQuery aims at leveraging CSS, HTML and JavaScript • Advantages • Lightweight • Easy to learn using familiar CSS syntax and intuitive • Many plugins available • Easy to extend and compatible • It’s on Microsoft’s radar • Rich community $('#something').hide().css('background', 'red').fadeIn();  You can read this, right?

  25. Microsoft and jQuery • Included with Visual Studio in both WebForms and MVC projects • Can be used with or without ScriptManager • ScriptManager can be used to compress and combine scripts • IntelliSense available • CDN support • Microsoft is contributor to jQuery • Proposed (and accepted) templating, data linking and globalization

  26. Script, don’t get in my way! • jQuery helps us writing Unobstrutive JavaScript code • You don’t want to mingle style with HTML • Why would you want to mingle behavior with HTML? • This will become a heavy job without jQuery! <script type="text/javascript"> window.onload = function() { document.getElementById('testButton').onclick = function() { document.getElementById('xyz').style.color = 'red'; }; }; </script> This code is downloaded every time

  27. jQuery fundamentals: $ • $ function (aka jQuery() function) returns • A JavaScript object containing an array of DOM elements • In the order they were found in the document • Matching a specified selector (for example a CSS selector) • Known to mankind as a wrapper or wrapped set • It returns the same group of elements, can be chained Finds all DIVs with Class someClass and Sets them visible $("div.someClass").show(); To the same set, this adds another class $("div.someClass").show().addClass("SomeOtherClass");

  28. jQuery fundamentals: the ready handler • Script execution should wait until DOM elements are ready • You say: window.onload? • Sadly, this waits for everything to be loaded, including images etc • Script execution is too late • Instead, we need to wait only until the DOM tree is created • Can be difficult in cross-browser situations • Easy-peasy with jQuery $(document).ready(function() { $("div.someClass").show(); }); $(function() { $("div.someClass").show(); });

  29. jQuery fundamentals: selectors • At the core of jQuery lies its selector engine • Can be used to select elements based on names, attribute, position... • $() is heavily overloaded • Making a selection • Creating new HTML elements

  30. jQuery fundamentals: selectors Selects all a’s with someClass applied within a paragraph • Most basic: CSS selectors • Can be combined • Child selector • Attribute selector $("p a.someClass") Also includes all DIVs on the page $("p a.someClass, div") Selects all links, directly in an LI, within an UL with someList class $("ul.someList > li > a") Selects all links that contain a reference to my site $("a[href*='http://www.snowball.be']") $("span[class^='some']") Select all SPANs that have a class Select all SPANs whose class attribute starts with some $("span[class]")

  31. jQuery fundamentals: selectors Selects first A we can find on the page • Position • Psuedo-classes (CSS filter selectors & custom selectors) $("a:first") Selects the “even” DIVs on a page $("div:even") Selects the first cells within a table named someTable $("table#someTable td:first-child") $("input:checked") Selects checked inputs (including the ones that weren’t checked initially) $(":password") Selects all INPUTs of type password Selects all ‘not- checked’ inputs $("input:not(:checked)")

  32. demo Selecting elements using selectors

  33. jQuery fundamentals: creating elements • $(‘...’) selects an element <> $(‘<li>’) creates an element • Attributes can be passed using JavaScript object $(function(){ $('<div>I’m off</div>') .appendTo('body'); $(function(){ $('<img>', { src: 'someImage.jpg', alt: 'Some nice image' }) .appendTo('body');

  34. demo Creating elements using $

  35. Working with the result of $ • Once we have a wrapped set, we can go wild with it! • Handle the set as a whole • Work with individual elements

  36. Working with the result of $ (2) • A wrapped set is like an array of elements, normal “array operations” can be done on it • Check the size • Access an indiviual element • Loop over the elements $('a').size(); $('a') [0]; $('a').get(0); $('img').each(function(n){ this.alt='image['+n+']'; });

  37. Working with the result of $ (3) • Set operations (continued) • Add and remove elements • Filter elements • Remember that we are always returning the set • Chaining is always possible! $("a[class]").add("a[href]"); $("a").filter("[href^='http://']"); $("a[class]") .add("a[href]") .filter("[href^='http://']") ...;

  38. demo Working with the set

  39. Attributes • When we want to change how an element looks, we can change its attributes • jQuery provides the attr() method • 2 variations based on number and types of parameters • Read a specified property from first element in wrapped set • Set a property on all elements in the wrapped set (0 or more) • Can also accept a function • Attr() helps us dealing with browser-dependencies (again) • jQuery float attribute refers to styleFloat in IE, cssFloat in others $("#myImage").attr("alt"); $('#myImage').attr('alt', ‘Me in Paris'); $('a[href^=http://']).attr('target ', 'blank‘);

  40. Attributes (2) • jQuery makes it easy to apply and remove CSS classes • addClass(), removeClass(), toggleClass() and hasClass() • Changing indiviual CSS elements is supported • css() can be used to get or set CSS on an element $('#mydiv').css("background-color","yellow");

  41. Working with elements • html() can be used to get or set the content of an element • text() can retrieve combined textual content of all elements, including their children • If the elements are form elements, we need to use val() Retrieves the HTML content Of mydiv $('#mydiv').html(); $('input:checkbox:checked').val(); Retrieves the value from a checked checkbox

  42. demo Working with attributes

  43. Events • A bit of history • Once upon a time, a browser called Netscape introduced an event model, often referred to as DOM Level 0 Event Model • Creates event handlers as references to a function on a property • Not what we need if we want to create Unobtrusive JavaScript • Only one event handler per element for specific event • Only got standardized until DOM Level 2 Event Model • Based on a system of event listeners (addEventListener) • IE decided to go its own way (attachEvent) • Using event was a real mess because of browser dependencies • jQuery comes to the rescue

  44. jQuery events • bind() is where it all starts • Binds a function to any event on any DOM element • Works in any browser, jQuery hides the details for us • Possible to bind more than one event handler for an event on on element • one() removes itself after event handler executed $('#myimg') .bind('click', function(event){alert(Hello TechEd!');} );

  45. Live and let die • bind() is OK for existing elements • live() allows us to create event handlers for elements that don’t exist (yet) • die() removes the live()-created event handlers $('.someClass') .live('click', function() { //do something }); If new elements match the selector, they get this event handler as well $(".someClass").die("click")

  46. demo Events

  47. Animations and effects • Core jQuery has some basic effects • More are available in jQuery UI • Should be used with caution! • Most basic ‘animation’ is hiding/showing an element • hide(): sets display:none on the element • show(): sets display to inline/block • toggle(): sets visible is hidden and vice-versa • Methods are overloaded, accepting • Speed • Callback

  48. Animations and effects (2) • Elements can also be gradually added/removed • slideDown() and slideUp() • Fading in is supported as well • fadeIn() and fadeOut() • animate() is mother of all animations • Using ‘target values’ for style properties, jQuery will animate the transition Change the opacity with a slow animation $('.someClass').animate({opacity:0.25},'slow');

  49. demo Animations

  50. Ajax in the past • When we were all young (in 1998), Microsoft introduced the ability to perform asynchronous requests from script (ActiveX) • Later, other browsers implemented a standard, the XMLHttpRequest • IE6 uses an ActiveX object • Result is that we need to do checks • Again... jQuery to the rescue! if(window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } Looks ugly, doesn’t it?

More Related