Categories

(111)
(57)
(102)
(16)

Writing jQuery plugin

16.03.2011
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 bestplugin 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 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 slideslength 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 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 thatthe 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.

5 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 enough...
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.

...
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...

Need a quote? Let's discuss the project

Are you looking for someone to help you with your Drupal Web Development needs? Let’s get in touch and discuss the requirements of your project. We would love to hear from you.

Join the people who have already subscribed!

Want to be aware of important and interesting things happening? We will inform you about new blog posts on Drupal development, design, QA testing and more, as well news about Drupal events.

No charge. Unsubscribe anytime