Categories

(83)
(69)
(8)
(34)
(74)
(149)

Writing jQuery plugin

16.03.2011
Пишемо jQuery плагін
Author:

Either one knows what jQuery is, or one is just starting studying it, this article on how to write one's own jQuery plugin will be interesting for every Drupal developer. It’s very easy to do that, anyway. After you have read this article, you’ll be able to create your own plugins.

To write your own plugin, you will have to declare jQuery.fn object first, for example jQuery.fn.bestplugin where the best plugin will be the name of your plugin. That’s how it will look like:

jQuery.fn. bestplugin = function() { 
// your code will be here
 };

As you can see, though, jQuery stands instead of the usual $ sign. In order to use $, we'll have to prevent our plugin from conflicting with other JavaScript libraries, hence we'll name $ the following way:

(function( $ ){ 
 $.fn.bestplugin = function() {
   // your code will be here 
 }; 
})( jQuery );

For the sake of illustrating, I have chosen a plugin utilized in the case of ordinary image slideshow:

(function($) {
  $.fn.bestplugin = function(options) { 
    var options = $.extend({      // Declaring settings by default that can be reset in plugin call
      timeOut: 2000,
      animateTime: 1000,
      opacity: 0.5
    },
    options);
    return $(this).each(function() { //return is used to continue a chain of calls of the given object
      var container = $(this),
      slides = $(this).children(),
      id,
      slidesLength = slides.length;
      container.css('position', 'relative');
      slides.each(function() {
        $(this).hide().css({
          'opacity': options.opacity,
          'position': 'absolute',
          'left': 0,
          'top': 0
        });
      });
      var Show = function() {
        id = id || 0;
        var currentSlide = slides.eq(id);
        console.log(currentSlide);
        currentSlide.show().animate({
          opacity: '1'
        },
        options.animateTime,
        function() {
          setTimeout(function() {
            currentSlide.animate({
              opacity: options.opacity
            },
            options.animateTime,
            function() {
              currentSlide.hide();
              id++;
              if (id == slidesLength) {
                id = 0
              };
              Show();
            });
          },
          options.timeOut);
        });
      }
      Show();
    });
  };
})(jQuery);

Let’s have a closer look at how it's working:

 var options = $.extend({      //Объявление настроек по умолчанию, которые можно переопределить в вызове плагина
      timeOut: 2000,
      animateTime: 1000,
      opacity: 0.5
    },
options);

This part of code is responsible for defining the plugin parameters; settings that are specified here will be activated by default, unless they have been changed in the plugin call function.

var container = $(this),
      slides = $(this).children(),
      id,
      slidesLength = slides.length;

Here you can see the variables for the container with images, a selector to which the plugin script will be applied to, the slides and slides length and global variable ID are defined.

var Show = function() {
        id = id || 0;
        var currentSlide = slides.eq(id);
        currentSlide.show().animate({
          opacity: '1'
        },
        options.animateTime,
        function() {
          setTimeout(function() {
            currentSlide.animate({
              opacity: options.opacity
            },
            options.animateTime,
            function() {
              currentSlide.hide();
              id++;
              if (id == slidesLength) {
                id = 0
              };
              Show();
            });
          },
          options.timeOut);
        });
      }

The very function of the slideshow is described here, with the animation features description added, which results in concurrent effects of image popping up and disappearing. As each image is being shown, its ID gets increased by 1 so as the forwarding to next slide to be affected. Then check-out: if (id == slidesLength) { id = 0 }; once we got to the last slide and want the slide show to keep going as starting from the beginning, ID variable shall be given 0 value.

As you can see, show function calls itself so that the slideshow could work. Next, at the very ending of the plugin, we call show() in order to start the function. The coding of the plugin is thus completed.

That’s the approximate HTML structure that you’ll require to keep the plugin operational:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Slideshow</title>
    <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="js/jquery.bestplugin.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    <link type="text/css" href="style.css" rel="stylesheet" />
    </head>
 
    <body>
 
        <div id="wrap">
            <div id="img-container">
                <img src="img/image1.jpg" alt="" />
                <img src="img/image2.jpg" alt="" />
                <img src="img/image3.jpg" alt="" />
                <img src="img/image4.jpg" alt="" />
                <img src="img/image5.jpg" alt="" />
                <img src="img/image6.jpg" alt="" />
                <img src="img/image7.jpg" alt="" />
            </div>
        </div>
    </body>
</html>

Whereby, in HEAD you’ll have to activate jQuery library, the plugin itself and your CSS.

To introduce the plugin into your file script, you’ll have to write down the following :

$(document).ready(function(){
$('#img-container').bestplugin({ // Reset plugin settings here if necessary
    opacity: 0.5,
    timeOut: 3000,
    animateTime: 500});  
});

That’s about it. I wish you the best of luck in studying this wonderful jQuery framework.

6 votes, Rating: 5

Read also

1

When registering on a site a user will normally be asked for password verification which is required in Drupal by default.

2

It happens very often that sorting on a specific criterion should be done. Views, Nodequeue, Flag and other similar modules are used for that. But sometimes functional of these modules is not...

3

Pressflow is Drupal’s distributive that provides advanced efficiency and scaling. It’s developed by the guys from Four Kitchens Company.

4

I was asked many times how to translate element <Any> in drop-down list in filter of views module. Yes! It can’t be done in a standard way by interface translation.

5

What’s CDN? Content Delivery Network or Content Distribution Network, CDN – geographically distributed network infrastructure which allows optimizing delivery and distribution of content to the...

Subscribe to our blog updates