Card Set Information

2010-07-20 16:57:04

jquery notes
Show Answers:

  1. plugins
    A jQuery plugin is simply a new method that we use By extending the prototype objectwhenever you call jQuery() you’re creating a new jQuery object, with all of jQuery’s methods inherited.(function($){$.fn.myNewPlugin = function() { return)extend jQuery’s prototype object, and that’s what’s happening on this line:$.fn.myNewPlugin = function()This has the effect of creating a “private” scope that allows us to extend jQuery using the dollar symbolwithout having to risk the possibility that the dollar has been over-written by another library.The this keyword within the new plugin refers to the We wouldn’t want to break this convention so we return the this object. return this.filter('a').each(function()$.fn.showLinkLocation = function() { return this.filter('a').append(function(){ return ' (' + this.href + ')'; }); }; }(jQuery));Notice also that we’re not using the attrmethod to retrieve the href attribute, because the native DOM API gives us easy access with the aptly named href property.$.fn.fadeInAndAddClass = function(duration, className)return this.fadeIn(duration, function(){ $(this).addClass(className);Google is your best initial resource for locating pluginsjQuery mailing list or the #jquery IRC channelEnsure that the plugin is well-documented, and look for the author to provide lots of examples of its use. read Signs of a poorly written jQuery plugin by Remy Sharp(function($){.toggleClass(c);(jQuery)read Mike Alsup’s essential post, A Plugin Development Pattern.Building Stateful jQuery Plugins by Scott Gonzalez.plugin must contain a namespacelimitation that namespaces be exactly one level deepnotice
  2. AJAX
    (XHR) allows browsers to communicate with the server without requiring a page reload.Asynchronous JavaScript and XMLcode sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the responserest of your code continues to execute while the request is being processedJSON (JavaScript Object Notation)In general, Ajax does not work across domains.The GET method should be used for non-destructive operationsGET requests may be cached by the browserGET requests generally send all of their data in a query string.POST requests are generally not cached by the browsera query string can be part of the URL, but the data tends to be sent separately as post data.For transporting JSON-formatted data, which can include strings, arrays, and objectsif the JSON data sent by your server isn’t properly formatted, the request may fail silently. use built-in language methods for generating JSON on the server to avoid syntax issues.JSONuseful for sending both HTML and data at the same timeResponses can only be handled using a callback.$.get('foo.php', function(response) { console.log(response); });In general, Ajax requests are limited to the same protocol (http or https), the same port, and the same domain as the page making the request. This limitation does not apply to scripts that are loaded via jQuery’s Ajax methods.espond to your request with a script that can be loaded into the page using a <script> tag,wrapped in a callback function you provideXHR panel of Webkit Inspectorrequest headers, response headers, response content, The $.ajax method is particularly valuable because it offers the ability to specify both success and failure callbacks.its ability to take a configuration object that can be defined separately makes it easier to write reusable code.url : 'post.php',// the data to send // (will be converted to a query string)data : { id : 123 },method : 'GET',dataType : 'json',success : function(json)<div class="content"/>jsonerror : function(xhr, status)complete :verify that the Content-type header is accurate for the data typefor JSON data, the Content-type header should be application/json.asyncNote that if you set this option to false, your request will block execution of other code until the response is received.cacheWhen set to false, the URL will simply have a cachebusting parameter appended to it.completeThe function receives the raw request object and the text status of the request.contextBy default, this inside the callback function(s) refers to the object originally passed to$.ajax.dataThe data to be sent to the server. This can either be an object or a query string, such as foo=bar&baz=bim.dataTypeBy default, jQuery will look at the MIME type of the response if no dataType is specified.a two-part identifier for file formats on the InternetjsonpThe callback name to send in a query string when making a JSONP request. Defaults to “callback”.successThe function receives the response data (converted to a JavaScript object if the dataType was JSON)timeoutThe time in milliseconds to wait typeThe type of the request, “POST” or “GET”. Defaults to “GET”.If you don’t need the extensive configurability of $.ajax, and you don’t care about handling errors, the Ajax convenience functions provided by jQuery can be useful,terse$.get$.post$.getScript$.getJSONPerform a GET request, and expect JSON to be returned.following argumentsurldataOptional.object or a query string,success callbackdata type$.get('/users.php', { userId : 1234 }, function(resp) { console.log(resp);$.getScript('/static/js/myScript.js', function() { functionFromMyScript();$.getJSON('/details.php', function(resp) { $.each(resp, function(k, v) {$('#newContent').load('/foo.html');$('#newContent').load('/foo.html #myDiv h1:first', function(html) { alert('Content updated!');$('#myForm').serializeArray();[ { name : 'field1', value : 123 }, { name : 'field2', value : 'hello world' } ]jsonp : 'callback',: 'select title,abstract,url from search.news where query="cat"', format : 'json'success :responsebind Ajax events to $('#loading_indicator') .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); });$this.data('target', $target);href = $a.attr('href'),$target.load('data/blog.html ' + id);name<option value=""><option value="monday"></select>var cachedResponse = null;$('<img/>') .attr('src', daySpecial.image)srcvar val = $select.val()url : 'json/specials.json',cachedResponse = specials;<select name="day"><option value="">Select</option></select>
  3. effects
    • $('div.old').fadeOut(300, function() { $(this).remove(); });if ($thing.length)lets you animate to a set value, or to a value relative to the current value.{ left : "+=50", opacity : 0.25 }""{ left : [ "+=50", "swing" ], opacity : [ 0.25, "linear" ] },$('h1').show(300).delay(1000).hide(300);You can also create custom animations of arbitrary CSS properties..show.fadeInAnimate the opacity of the selected elements to 100%.slideDown.slideToggle$('h1').fadeIn(300);$('h1').fadeOut('slow');speeds:jQuery.fx.speeds.blazing = 100;
    • fx.offThis can be especially useful when dealing with older browsers; you also may want to provide the option to your users.(function($)functionvar=function(e)e.preventDefault();var=thisvar=$h3.next('p');$p.slideToggle();$h3.parent().siblings():visible(jQuery);$(document).ready(function().hover(function() {.show().css({'cursor':'pointer'})///pointer is actually pointing finger