Javascript And J Query


Published on

Some advanced Javascript with a survey of interesting jQuery features

1 Comment
1 Like
  • hey, please make this downloadable :) I want to read it offline.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Javascript And J Query

  1. 1. Presented by Arsalan Ahmed<br />jQuery Goodness – part 1<br />
  2. 2. Different species than POCOs<br />Properties added dynamically upon first use<br />A typo creates a new property – yikes!<br />Properties accessed via: <br />Dot notation (Object.Property)<br />Subscript notation (Object[‘Property’])<br />Literal syntax:<br />varsomeObj = { someProp: ‘some value’, otherProp: 2 };<br />Variables are properties. Equivalent statements in the global scope:<br />var prop = ‘x’; window.prop = ‘x’; prop = x;<br />Objects in Javascript<br />
  3. 3. Functions are also objects<br />Functions can <br />contain other functions!<br />have properties!<br />be assigned to a property<br />be passed to a method and also returned from it<br />Smoke and mirrors. Equivalent statements:<br />function someFunc(someParam) { return ‘wow!’ }<br />someFunc = function(someParam) { return ‘wow!’ }<br />window. someFunc = function(someParam) { return ‘wow!’ }<br />So what’s the deal with these functions?<br />
  4. 4. Local variables stick around<br />Great way to avoid using global variables<br />Avoids potential naming conflicts<br />Example:<br />var f = function() {<br />varartifactID = 5553333;<br /> return function() {<br />processArtifact(artifactID++);<br /> }<br />}<br />And then we found closure…<br />
  5. 5. Structure and behavior separated<br />Behavior can change independent of structure<br />Avoids spaghetti code<br />Event handling not performed inline<br />Unobtrusive Javascript<br />
  6. 6. Start<br />Assume javascript not available<br />Implement acceptable functionality<br />End<br />Layer javascript goodness on top<br />Implement javascript-enhanced functionality<br />Degrade gracefully when javascript cannot be used<br />Progressive Enhancement<br />
  7. 7. jQuery uses CSS-style selectors<br />Creates wrapped sets when passed to jQuery<br />jQuery(‘tr:nth-child(2)’)<br />Alias: $(‘tr:nth-child(2)’)<br />Class selectors slower than ID selectors<br />What’s with these selectors?<br />
  8. 8. p > a [all anchor tags, direct children of p tags]<br />div.items a [all anchor tags, descendents of div tags with class of items]<br />div.items:has(a) [all div tags with a class of items that contain anchor tags]<br />a[href^=‘http://’] [all anchor tags, href attribute starts with http://]<br />div#coolness.gunit [all div tags with the id of coolness and class of gunit]<br />Selectors: Child, Container, Attribute<br />
  9. 9. table#itemListtr:even[all even rows in the table with an ID of itemList]<br />:checkbox:checked:enabled[all enabled and checked checkboxes]<br />:enabled:visible[all enabled and visible elements]<br />Selectors: Filters<br />
  10. 10. Function Context: a friendly chameleon<br /><ul><li>The magical ‘this’
  11. 11. In wrapper methods, set to the current element
  12. 12. Within functions, ‘this’ => function context of the invocation</li></ul>x.desc = ‘x’; y.desc = ‘y’;<br /> = function() { alert(this.desc); <br />}<br />; [outputs ‘x’]<br />; [outputs ‘y’]<br />
  13. 13. var counter = 1;<br />$(window).bind('click contextmenu', function() {<br />$('#demo').css('font-size', '40')<br /> .append('<div>Timestamp: ' + new Date() + ', counter = ' + counter + '</div>');<br /> counter++;<br />});<br />Selectors and Closures Demo<br />
  14. 14. Methods on wrapped sets<br />size() => # of elements contained within<br />first(), last() => first or last element within<br />toArray() => array of DOM elements<br />not(exp), filter(exp) => copy of original minus exp<br />exp = selector, function, element, or array<br />slice(begin, end) => subset within the indices<br />each(iterator) => invokes iterator for every element<br />end() => back up to previous wrapped set<br />andSelf() => merges two previous wrapped sets to another<br />Manipulating wrapped sets<br />
  15. 15. Browsers implement events differently<br />Event object creation differs<br />Event propagation differs<br />Event handler location differs<br />In other words, it’s great fun!<br />Browser Event Models<br />
  16. 16. Handlers defined inline<br />Limit: One handler per event<br />elem.onclick = function(event) { … }<br />Event bubbles up through the DOM<br />Return false to cancel event propagation<br /> <form onsubmit=“return false;” …<br />Basic Event Model<br />
  17. 17. DOM Level 2 Event Model<br />Allows multiple event handlers per event<br />addEventListener('click', function(event) { ... }, useCapture)<br />useCapture = true => handle capture phase (top to target) event <br />useCapture = false => handle bubble phase (target to top) event<br />Not supported by IE!<br />IE event model uses legacy event names (onclick vs. click)<br />In IE event model, event instance not passed to handler (use window.event)<br />Newer, Fancier Event Model<br />
  18. 18. Works on all browsers<br />Allows multiple event handlers per event<br />Uses standard event names<br />Event instance passed as parameter to handler<br />Like Level 2 model but no capture phase<br />Lots of ways to attach handlers to events<br />jQuery Event Model<br />
  19. 19. Multiple Event Handlers Demo<br />
  20. 20. Event Bubbling Demo<br />
  21. 21. Fun With Event Handlers<br />
  22. 22. Hijacking form posts<br />Use Ajax POST requests<br />Used in ASP.NET Update Panel<br />jQuery makes it super simple<br />Encourages progressive enhancement<br />The wonderful world of Hijaxing<br />
  23. 23. $('form').submit(function(event) {<br />event.preventDefault();<br /> $.ajaxSetup({<br /> type: 'POST',<br /> timeout: 10000,<br />dataType: 'html'<br /> });<br /> $.ajax({<br />url: 'http://localhost/Demo/Information.asmx/GetInfo',<br /> …<br /> success: function(response) { $('#info').html(response) }<br /> });<br />});<br />Hijaxing: Code Sample<br />
  24. 24. jQuery.event.special.eventName<br />Special Events have these optional methods:<br />setup<br />Executes when first event handler is bound to element<br />teardown<br />Executes when last event handler is bound to element<br />add<br />Executes when each event handler is added to element<br />remove<br />Executes when each event handler is removed from element<br />_default (not that interesting)<br />Executes after event has bubbled to “document”<br />Executes for custom events fired by “trigger” method <br />The Wonders Of Special Events<br />
  25. 25. Setup event handlers<br />Calculate width and height<br />Element position<br />Ancestry<br />Progeny<br />Containment<br />Filter and Each<br />Merge and Extend<br />Quick Rundown of jQueryConfusicons<br />
  26. 26. bind() attaches handler to all elements in wrapped set<br />bind() allows binding multiple events with a handler<br />live() attaches handler to current and FUTURE elements via DOM Scripting<br />live() binds only one event<br />live() can only be invoked on the ORIGINAL wrapped set<br />$('#item', 'tr').closest('table').live('click', function() { ... });<br />delegate() attaches handlers for current and FUTURE elements<br />delegate() allows filtering to bind to a subset of wrapped set<br />$('#item').delegate('a', 'click', function() { ... });<br />Binding Event Handlers<br />
  27. 27. css('width') and css('height') return strings<br />e.g. '200px‘<br />width() and height() return integers<br />width() and height() can return dimensions of window and document<br />css('width') and css('height') throw errors for above<br />css('width') and css('height') not always reliable<br />IE returns ‘auto’ for computed dimensions<br />Width And Height<br />
  28. 28. position() calculates the offset from nearest ancestor with relative positioning<br />If none found, defaults to document<br />offset() ALWAYS calculates the offset from document<br />Element Position<br />
  29. 29. parent(selector) returns the immediate parent if it matches the selector<br />parents(selector) returns all ancestors that match the selector<br />closest(selector) returns the closest ancestor that matches the selector<br />Ancestry<br />
  30. 30. children(selector) returns immediate children that match the selector<br />find(selector) returns all descendants that match the selector<br />Progeny<br />
  31. 31. not(selector) returns filtered elements that do not match the selector<br />is(selector) returns true if any element in the wrapped set matches the selector<br />$('p:not(.info)') SAME AS $('p').not(‘.info’)<br />$(‘table:has(tr)’) returns all tables with at least one row<br />Containment<br />
  32. 32. filter(selector) returns wrapped set of elements that match the selector<br />filter(function) returns wrapped set of all elements for which the function returns true<br />each(function) executes the function over all elements in the wrapped set<br />$.each(function) runs on any array like object<br />function context set to the current element being processed<br />Filter and Each<br />
  33. 33. $.merge() combines 2 arrays and saves result to first array<br />$.extend() combines 2+ objects and saves result to first object<br />jQuery.extend([recursive?], target, object1, ... )<br />Common idiom to use $.extend() to provide default values<br />function(options) {<br />var settings = $.extend({<br /> prop1: 200,<br /> prop2: null,<br /> },<br /> options || {} );<br />}<br />Merge And Extend<br />
  34. 34. Simply assign a function to a property on jQuery ($)<br />Good Idea: Namespacing<br />$.kCura = {};<br />$.kCura.somethingWonderful = function(awesomeness) {<br /> …<br />};<br />Bad Idea: Assume $ has not been appropriated<br />(function($) {<br /> // awesome code goes here<br />}) (jQuery);<br />Extending jQuery: Utility Functions<br />
  35. 35. Create a property on the fn object of jQuery<br />Function context within main body refers to wrapped set<br />Use each() to work on elements individually<br />If iterating via functions, above iteration automatic<br />$.fn.kCurafy = function() {<br />this.each(function() { <br />makeAwesome($(this).data(‘identifier’));<br /> }<br /> function makeAwesome(id) { … }<br />};<br />Usage Example: <br />$(‘img’).kCurafy();<br />Extending jQuery: Wrapper Functions<br />
  36. 36. Questions?<br />