jQuery

Articles
Deffered
Event

How to check the version of jQuery?

$().jquery;
jQuery.fn.jquery;

How to map $ to jQuery?

(function($){})(window.jQuery);

This is if you have some other library loaded and you want $ to represent jQuery.

How to obtain the raw DOM element?

jQuery('id').get(0)

Is event handling only applicable to DOM elements?

No. Event handling is not only applicable to DOM elements (or UI elements). It is for back-end programming too. It is known as "event driven", observer / dispatcher pattern. jQuery allows event driven architecture to be applied to javascript object, as well as native object. See Custom Event

What is custom event?

No. Event handling is not only applicable to DOM elements (or UI elements). It is for back-end programming too. It is known as "event driven", observer / dispatcher pattern. jQuery allows event driven architecture to be applied to javascript object, as well as native object. See Custom Event

Does jQuery support the beforeunload and error event on the window object?

No. The beforeunload and error events on the window object use nonstandard conventions, and are not supported by jQuery (jQuery does not offer a convenient method for these events). You must attach the handler directly to the window object.

jQuery has a convenient method name error() which is a shortcut for:

.bind('error', function(event){...});

The error event is sent to elements such as images. It is called if the element is not loaded correctly.

The error event may not be fired correctly when the page is served locally. Since error relies on normal HTTP status code, it will generally not be triggered if the URL use the file protocol.

jQuery error event handler should not be attached to the window object. The browser fires the window's error when a script error occurs. However, the window error event receives different arguments and has different return value requirements than the conventional event handlers.

// Hide javascript errors from the user.  Use this at your own risk
// If you need to log the line numbers where the event happen, etc, look elsewhere on this wiki
$(window).error(function() {
    return true;
});

What is event delegation?

Ability to specify an event handler for all (now and in the future) elements that match the given selector, based on a specific set of root elements. Sample usage:

$("table").delegate("td", "hover", function(event) {
    $(this)....
});

In this example, "table" is a selector represent the parent (or "context") element which is expected to be present in the DOM at all time, and "td" is a selector representing child elements (or future child elements). You should specify the selector for the parent ("context") element, and not (ab)use "body", so to prevent unnecessary bubbling.

Signature:

$("parent_selector").delegate("child_selector","event_type", function(event) {});   // version added: 1.4.2
$("parent_selector").delegate("child_selector","event_type",{event_data},function(event){});  // version added: 1.4.2

Since .live() method handles events once they are propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the "context" element (the parent element which they are delegated). Event handlers on any element below it will already have been executed by the time the delegated event handler is called.

Will event delegation work for all selectors?

No. It is worth noticing that not *all* selectors will work as expected within .delegate(). While $('#mydiv').find('>p').click(function(){}) work. $('#mydiv').delegate('>p','click',function(){}) will not work. To make it work, try:

$('#mydiv').delegate('#mydiv > p','click', function(){});

What are the benefits of using event delegation?

  • The same event handler can be defined for existing elements as well as future elements.
  • Because only one event handler is defined, and bound to the parent ("context") element, the number of bound event handlers is reduced (as compared to the event handler is bound to all the child elements). This reduces memory usage.

Can we use event delegation with custom events?

Yes:

$("body").delegate("p", "myCustomEvent", function(event){...});
...
$("p").trigger("myCustomEvent");

When we think of "custom event", we may think that "custom event" is only associated with non-DOM object. However, there is no reason why custom events cannot be applied to DOM objects / elements. Custom events are not triggered by the browser, so our code has to trigger the custom event as above. If we have a system where our objects are like the DOM (has parent-child relationship between nodes), there is no reason why we cannot apply custom events to our objects. The DOM is just a medium that allow event delegation (or event bubbling) to work

Can we use event delegation with namespace?

The answer should be yes.

Can we use event delegation with more than one event type?

Yes. If we have an event handler that is applicable to more than one event types, we can delegate them in one statement. eventType: a string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.

Using event delegation, can we pass extra information to the event handler at delegation time?

Yes. eventData: A map of data that will be passed to the event handler.

What happens when an event reaches an element?

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

How can you bind a handler to multiple events in one shot?

If you have an event handler that is applicable to multiple events, you can bind this handler to multiple events in one shot:

$("#foo").bind('mouseover mouseout', function(event) {...});

You can specify multiple events (separated by space).

How to bind multiple events to multiple elements in one shot?

$("#foo").bind({
    'click': function(event) { ... },
    'mouseover': function(event) {...}
});

Within the body of your event handler, what is the meaning of the this keyword?

Within the handler, the keyword this refers to the DOM element which the handler is bound. To make use of the element using jQuery, wrap it inside the normal $() function:

$(this)

How can your event handler gain access to the event object?

When your handler is called, the event object is passed to your handler as the first parameter.

What does returning false from inside your handler mean?

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation()

How to pass additional information (at the time the handler is bound) to your event handler ?

The optional eventData parameter to bind() is not commonly used. When provided, this argument allows you to pass additional information to the handler. One handy use of this parameter is to work around limitation of closures. For example, suppose that we have two event handlers that both refer to the same external variable:

var message = 'Spoon';
$('#foo').bind('click', function() {
    alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
    alert(message);
});

Because the handlers both refers to messages, both will display 'Not in the face!' when triggered. To sidestep this problem, we can pass the message using eventData:

var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
    alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
    alert(event.data.msg);
});

This time, the variable is not refered to directly within the handlers. Instead, the variable is passed in by value through eventData, which fixes the value at the time the event is bound. The first handler now display 'Spoon!'. The second handler now display 'Not in the face!'

How to unbind all click event handlers that are bound to a given element?

$('#foo').unbind('click');

If you have to use unbind() like this, chance are that you are doing something wrong. End user of your plugin may have other handlers attached to the same element. If you want to remove just your click handler, use namespace.
How to unbind all handlers attached to a given element?

$('#foo').unbind();

This removes all handlers regardless of type. If you have to use unbind() like this, chance are that you are doing something wrong. End user of your plugin may have other handlers attached to the same element.

How to unbind all event handlers in a namespace on an element, regardless of event type?

$('#foo').unbind('.mynamespace');

How to unbind a handler from within itself?

For example, suppose that we wish to trigger an event handler on three times:

var timesClicked = 0;
$('#foo').bind('click', function(event) {
    alert('The quick brown fox jumps over the lazy dog.');
    timesClicked++;
    if (timesClicked >= 3) {
        $(this).unbind(event);
    }
});

Noticed that unbind() is called with the event object. The handler in this case must take a parameter, so that we can capture the event object and use it to unbind the handler after the third click. The event object contains the context necessary for unbind() to know which handler to remove.

What are the different between trigger() and triggerHandler()?

  1. While trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occuring event. To trigger handlers bound via jQuery without also triggering the native event, use triggerHandler(). The triggerHandler() method does not cause the default behavior of an event to occur (such as form submission).
  2. trigger() will operate on all elements matched by the jQuery object. triggerHandler() only affect the first matched element.
  3. Events created with triggerHandler() do not bubble up the DOM hierarchy. If they are not handled by the target element directly, they do nothing.
  4. Instead of returning the jQuery object (to allow chaining), triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined.

How to pass additional information to your handler at the time the event is triggered?

Well, obviously, you have to use trigger() or triggerHandler(). The trigger() method takes eventType as the first parameter. It also takes a second parameter, which is passed to your handler as the second parameter (the first parameter for an event handler is always the event object).

How to create a jQuery event object?

var event = jQuery.Event("submit");
$("#foo").trigger(event);

How to pass arbitrary data through an event object using trigge()?

var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);

$("body").trigger({
    'type': 'logged',
    'user': 'foo',
    'pass': 'bar'
});

What is the benefit of using namespaced event?

Using namespaced event allows us to unbind or trigger some events of a type without affecting others. For example, you are the author of a plugin. On a page where your plugin is being used, the user may have an event handler attached to an element, which your plugin also attach to. You may want to trigger an event on that element (to invoke your handler), without invoking the other handler.

Also, as an author of a plugin, you may find yourself needing to unbind your handler, without unbinding other handlers. You can do this safely using namespace.

What is namespaced event?

Generally, when binding an event handler, you would do something like:

$('.class').bind('click',function(){});

However, sometimes, you want to unbind just a specific handler, or group of handlers (for example, all handlers bound by a plugin). Unfortunately, calling unbind:

$('.class').unbind('click');

will remove all bound handlers.

jQuery provides a concept called namespaced events. Simply add a namespace name (which can be the name of your plugin) to your event when you declare it. You can then reference that namespaced event both with unbind and trigger:

$('.class').bind('click.namespaceName',function(){});
$('.class').trigger('click.namespaceName');
$('.class').unbind('click.namespaceName');

Namespaced events will be unbound or triggered when their namespace is mentioned explicitly, or no namespace is mentioned at all.

If you've used the same namespace on multiple events, you can easily remove the bindings from all events at once:

$('.class').bind('click.namespaceName', function(){});
$('.class').bind('blur.namespaceName', function(){});
$('.class').unbind('.namespaceName');

Can we use multiple namespaces on our events?

Yes. As of jQuery 1.3, we can use multiple namespaces on our events:

$('.class').bind('click.a.b'), function(){});
$('.class').trigger('click.a');
$(.class').unbind('click.b');

What is the purpose of the proxy() method?

It makes it easy to use OOP for event handler:

$(document).ready(function() {
    function BaseObject(){
    this.sampleValue = 50;
    };
    BaseObject.prototype = { 
    init: function() {
        $(document).bind('click', {arg1:'value1',arg2:'value2'}, $.proxy(obj.showSampleValue, obj));
    },
    showSampleValue: function() {
         alert(this.sampleValue);
    }
    };
    var obj = new BaseObject();
    obj.init();
});

Inside your handler, the this keyword, which is normally the DOM element that cause the event, now is an object of BaseObject. If you need to know the DOM element that the event happen on, your handler need to accept the event object as argument (you can use event.currentTarget), or you can use arguments[0].

The proxy() method takes a function and returns a new one that will always have a particular context. This method is most useful for attaching event handlers to an element where the context is pointing back to a different object.

Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function, if passed the original.

Writing jQuery plugin:

jquery.easy_window.js

(function($) {
    //plugin code will go here...
})(jQuery);

By passing jQuery to a function that defines the parameter as $, $ is guaranteed to reference jQuery within the body of the function.

This anonymous function executes immediately when it is loaded (due to the last pair of parentheses). It takes one argument, the dollar sign, which is the jQuery object. This means that we can use any standard jQuery functionality using the $ sign as an alias.

(function($){
    $.fn.makeItBlue = function() {
        // Within the body of this method, the function context (this) refers to the wrapped set.
        // We can use all of the predefined jQuery command on it.
        // The function context (this) within the main body of a wrapped method refers to
        // the wrapped set, but when inline functions are declared within this function, they each
        // have their own function contexts.  You must take care when using 'this' under such
        // circumstances to make sure that it is referring to what you think it is.  For example, if 
        // you use each(), within its iterator function, 'this' references the DOM element for the 
        // current iteration.
        return this.css({'color': 'blue'});
     }
})(jQuery);

Unless the new wrapped method is intended to return a specifc value, it should always return the wrapped set.

If, for some reason, we need to deal with each wrapped element individually, the following pattern can be used:

(function($) {
    $.fn.easy_modal = function() {
        return this.each(function() {
            // Function body goes here -- 'this' refers to individual element
        }
    });
})(jQuery);

Each listener we defined will create a closure that includes the settings variable, so we can rest assure that, even though settings may appear to be transient, the state that it represents will stick around and be available to all the listeners we define.

Recall that our plugin function is defined within the body of another function — the function that we use to ensure that $ means jQuery. Therefore, any local variables defined within that outer function become part of the closure defined by our plugin function. What if we define the implementation function, which will name showPhoto() as a local variable in the outer function? That solves our issue nicely! Our showPhoto() will be available to the plugin function as part of its closure, but because it is declared locally to the outer function, it can't be seen from outside that function and has no opportunity to pollute any other namespace.

(function($) {
    var settings;
    $.fn.easy_modal = function(caller_settings) {
        settings = $.extend({
            'photoElement': '#photomaticPhoto',
            'transformer': function(name) {
                return name.replace(/thumbnail/,'photo');
            }, 
            'nextControl': null,
            'previousControl': null,
            'firstControl': null,
            'lastControl': null,
        }, caller_settings || {});
        // Note that we guard against a caller_settings that is null or undefined with ||{}, which supplies an empty
        // object if caller_settings evaluates to false (as we know null and undefined do).
 
        settings.photoElement = $(settings.photoElement);
        settings.thumbnails = this.filter('img');
        settings.thumbnails.each(function(n) {this.index = n;});
        settings.current = 0;
        settings.thumbnails.click(function() { showPhoto(this.index); });
        settings.photoElement.click(function() {
            showPhoto((settings.current + 1) % settings.thumbnails.length);
        });
        $(settings.nextControl).click(function() {
            showPhoto((settings.current + 1) % settings.thumbnails.length);
        });
        $(settings.previousControl).click(function(){
            showPhoto((settings.thumbnails.length + settings.current - 1) % settings.thumbnails.length);
        });
        $(settings.firstControl).click(function(){
            showPhoto(0);
        });
        $(settings.lastControl).click(function(){
            showPhoto(settings.thumbnails.length - 1);
        });
        showPhoto(0);
        return this;
    };
 
    var showPhoto = function(index) {
        settings.photoElement.attr('src', settings.transformer(settings.thumbnails[index].src));
        settings.current = index;
    };
})(jQuery);

This plugin demonstrate an important set of techniques - using closures to maintain state across the scope of a jQuery plugin and to enable the creation of private implementation functions that plugins can define and use without resorting to any namespace infringements.

JavaScript functions are first-class objects, and they can have their own properties like any other JavaScript objects.

Writing custom utility functions

Utility functions are defined as properties of jQuery (and therefore $). These functions are not intended to operate on DOM elements (that is the job of methods defined to operate on a wrapped set), but to either operate on a non-element JavaScript object or perform some other nonobject-specific operation. Examples: $.each(), and $.noConflict().

Adding a function as a property to an Object instance is as easy as declaring the function and assigning it to the object's property. So creating a trivial custom utility function should be as easy as:

(function($){
    $.say = function(what) {
        alert('I say ' + what);
    }
})(jQuery);

Provide public access to secondary functions as applicable.

/**
 * Your plugin name and a small description
 * Link to the project page and/or repositorry
 * Copyright (c) 2009 Your Name, licensed under Your License
 */
(function($) {
  $.fn.hilight = function(options) {
    debug(this);
 
    // build main options before element iteration
    var opts = $.extend({}, $.fn.hilight.defaults, options || {});
 
    // iterate and reformat each matched element
    return this.each(function() {
      $this = $(this);
 
      // build element specific options
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
 
      // update element styles
      $this.css({
        backgroundColor: o.background,
        color: o.foreground
      });
 
      var markup = $this.html();
 
      // call our format function
      markup = $.fn.hilight.format(markup);
      $this.html(markup);
    });
  };
 
  // private functions
  function debug($obj) {
    if (window.console && window.console.log)
      window.console.log('hilight selection count: ' + $obj.size());
  };
 
  // public functions
  $.fn.hilight.format = function(txt) {
    return '<strong>' + txt + '</strong>';
  };
 
  // plugin defaults
  $.fn.hilight.defaults = {
    foreground: 'red',
    background: 'yellow'
  };
})(jQuery);

Users can change the default settings:

$.fn.hilight.defaults.foreground = 'blue';

Plugin Development
Performance
Dimension
Custom Queue
Event
Tips and tricks
AJAX
Making the modal dialog library
Validation

http://masonry.desandro.com/?resources/jquery-masonry
http://layout.jquery-dev.net/
http://www.bramstein.com/projects/jlayout/jquery-plugin.html
http://blog.karachicorner.com/2011/09/jquery-flexible-font-size-plguin-fittext/
http://blog.karachicorner.com/2011/08/website-font-resize-jquery-plugin-jfontsize/
http://blog.karachicorner.com/2011/09/css3-transitions-jquery-image-slider-flux-slider/
http://blog.karachicorner.com/2011/09/free-jquery-content-slider-diapo/
http://blog.karachicorner.com/2011/08/awesome-jquery-content-slider-flexslider/
http://blog.karachicorner.com/2011/06/jquery-content-slider-with-thumbnails-captions-and-tooltips-awkward-showcase/
http://blog.karachicorner.com/2011/09/jquery-color-picker-plugin-excolor/
http://blog.karachicorner.com/2011/07/dropkick-jquery-dropdown-menus-plugin/
http://blog.karachicorner.com/2011/05/openjs-grid-%E2%80%93-easiest-customizable-jquery-datagrid/
http://blog.karachicorner.com/2011/06/gmap3-jquery-plugin-for-google-maps/
http://blog.karachicorner.com/2011/07/jquery-tooltips-plugin-bubble-shaped-tooltips-with-grumble-js/
http://blog.karachicorner.com/2011/08/file-browser-with-php-jquery-sfbrowser/
http://blog.karachicorner.com/2011/09/auto-complete-input-field-with-jquery-combogrid-plugin/
http://blog.karachicorner.com/2011/05/ninja-ui-jquery-plugin-to-create-beautiful-web-objects/
http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/
Google Powered Site Search with jQuery
14 Helpful jQuery Tricks, Notes, and Best Practices
Making Better Select Elements with jQuery and CSS3

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License