Make your first JQuery plugin in 2 minutes

To let you know how JQuery makes writing plugins very easy I will show you a practical demo of building one which should take a couple of minutes to build. This plugin adds rollover functionality to images so when a user rolls over an image; browser switch the displayed image with the image specified in the rollover attribute of the <img> tag.

Plugin:

(function ($) {
    $.fn.rollover = function () {
        this.find("img[rollover]").mouseover(function (evt) {
            //mouse over
            $(this).attr("originalSrc", $(this).attr("src"));
            $(this).attr("src", $(this).attr("rollover"));
            //mouse out
            $(this).mouseout(function () {
                $(this).unbind("mouseout");
                $(this).attr("src", $(this).attr("originalSrc"));
            });
        });
    };
})(jQuery);

Usage:

$(function () {
            $("#tiles").rollover();
});

Markup:

<div id="tiles">
       <img src="[some url]" rollover="[some url]"  />
       <img src="[some url]" rollover="[some url]"  />
</div>

See the result

Explanation:

(function ($) {
       //function code
})(jQuery);

This is called Immediately-Invoked Function Expression (IIFE) and from its name we can see that its just a function but its invoked immediately so its like making declaration and invocation in the same expression. You will also note that this function takes JQuery object as a parameter. We need to do this to be able to use the ($) symbol in our plugin code (the body of this function) without being afraid of other libraries that may use the same symbol.

$.fn.rollover = function () {
       //function code
}

This is where the magic begins; we are adding a rollover function to $.fn object. inside this function the (this) keyword will be the JQuery wrapped set that will invoke the rollover function in usage time. So we can start working on our DOM objects from this point to complete the plugin:

        
         this.find("img[rollover]").mouseover(function (evt) {
            //mouse over
            $(this).attr("originalSrc", $(this).attr("src"));
            $(this).attr("src", $(this).attr("rollover"));
            //mouse out
            $(this).mouseout(function () {
                $(this).unbind("mouseout");
                $(this).attr("src", $(this).attr("originalSrc"));
         });

For JsFiddle guys: http://jsfiddle.net/MnZxM/embedded/

Advertisements
This entry was posted in Software and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s