Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

9.5. Creating Event-Driven Plugins

Problem

You want your plugin to be controllable from the outside. One should be able to “tell” the plugin to do something at any time. There could be many instances (calls) of a plugin, but our action should only be executed in the context we provide.

Solution

One way to do this is indeed using events.

When a plugin is called, it binds functions on each matched element that once triggered, and it will perform the desired actions.

As a possible side solution, each time the plugin is called, instead of respecting the chaining, it could return an object that contains the bindings and allows external manipulation (use the plugin from Recipe 9.2).

This allows you to call the plugin many times on the same element without messing up the events.

Discussion

An example

We’ll now create a simple slideshow plugin. I’ll base this plugin on an existing plugin of mine called jQuery.SerialScroll.[19] I first thought of this approach when coding this plugin, and, I must say, it worked pretty well.

We’ll name our plugin slideshow. It will receive an <img> element and an array of URLs, and it will cycle the images. It will allow previous and next movement, jumping to a certain image, and also autocycling.

Let’s start with the basics:

(function( $ ){
    $.fn.slideshow = function(options){

        return this.each(function(){
            var $img = $(this),
                current = 0;

            // Add slideshow behavior...
        });
    };
 })( jQuery );

Now we’ll add a few local functions that will allow us to move to different images ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required