jQuery Text Slider Plugin

jQuery Text Slider Plugin

web solutions
English text only

When writing a plugin, usually there are a lot of things I keep in mind:

  • its functionality (obviously): which problem does it solve?
  • its usefulness: how many times will I (and others) use it?
  • its expandability: how can I add events, override methods, reuse it?
  • its style: is it syntactically correct, easy to read, well indented?

Well analyze these points in creating a new jQuery plugin, for a text slider.

The plugin should be able to connect a list of links to some lines of text, and slide them accordingly to the anchor points.

The requirements are then:

  • show the links;
  • define anchor points in some lines of text;
  • click on the link and slide the text up, showing only the text relative to the link.

The page is built as follows:

<div id="slideme">
  <ul class="menu">
    <li><a href="#fruits">Fruits</a></li>
    <li><a href="#vegetables">Vegetables</a></li>
  </ul>
  <ul class="slider">
    <li id="fruits">In broad terms, a fruit is a structure of a plant
that contains its seeds.</li>
    <li id="vegetables">The noun vegetable usually means an edible plant or
part of a plant other than a sweet fruit or seed.
This typically means the leaf, stem, or root of a plant.</li>
  </ul>
</div>

For the plugin to work, the markup should be structured as follows:

  • two unordered lists, identified by IDs or classes
  • inside the first list there should be <a> tags, with anchors to the second list <li> items;

We want to apply the text sliding effect to the slideme element, using the following HTML:

(function($) {
$.fn.anchorize(function(settings) {
  /* 1. check settings */
  /* 2. setup starting values */
  /* 3. cycle through each link */
}
})(jQuery);

First of all, we can check some settings, that can be overridden by the constructor:

/* 1. check settings */
settings = $.extend({
  menu: '.menu',
  target: '.slider',
  speed : 500,
  height: 200  
}, settings);

To retrieve the links from the slideme div, we can define some variables using those settings:

/* 2. setup starting values */
var container = this;
var menu = $(settings.menu, container);
var target = $(settings.target, container);

container.css({'position':'relative','overflow':'hidden'});
$('li:first', menu).addClass('active');
target.css("height", settings.height+"px");
$("li", target).css({"display":"none", "position":"absolute"});
$("li:first", target).css("display", "block").addClass("active");

For each link, we need to bind a click function, that’s used to trigger the slide action.

/* 3. cycle through each link */
$('li', menu).each(function() {
  // We use this to save the link variable
  var link = $(this);

  $('a', link).click(function() {
    /* 3.1. get current item to show and last shown */
    /* 3.2. show current content and hide last */
  }
}

We can easily get the items by using some classes that were applied before, and the anchors defined in the markup.

/* 3.1. get current item to show and last shown */
var oldCurrentItem = target.find('.active');
var currentItem = $($(this).attr("href"));

And then, we can modify the relative CSS

/* 3.2. show current content and hide last */
if(!currentItem.hasClass('active')) {
  currentItem
    .addClass('active')
    .css({'display':'block'});

  oldCurrentItem
    .removeClass('active')
    .css({'display':'none'});
}

Better still, we can animate (and create the full sliding effect) just adding a little spice to the current and last items:

/* 3.2. show current content and hide last */
if(!currentItem.hasClass('active')) {
  currentItem
    .addClass('active')
    .css({'top':settings.height+'px', 'display':'block'})
    .animate({top: 0}, settings.speed);

  oldCurrentItem
    .removeClass('active')
    .css('top', 0)
    .animate({
      top: -settings.height,
      opacity: 0
    }, settings.speed, function() {
      $(this).css('display', 'none');
    });
}

A little refinements will help us to create a little gem:

  • we add a sliding variable to prevent clicking when the item is currently sliding;
  • we check if we are clicking on the “already current” item;
  • we add some CSS class to the links when active.

The full code is then:

(function($) {
  $.fn.anchorize = function(settings) {
    settings = $.extend({
        menu: '.menu',
        target: '.slider',
        speed : 500,
        height: 200
      }, settings);

    var container = this;
    var menu = $(settings.menu, container);
    var target = $(settings.target, container);

    container.css({'position':'relative','overflow':'hidden'});
    $('li:first', menu).addClass('active');
    target.css('height', settings.height+'px');
    $('li', target).css({'display':'none', 'position':'absolute'});
    $('li:first', target).css('display', 'block').addClass('active');

    var sliding = false;
   
    $('li', menu).each(function() {
      // We use this to save the link variable
      var link = $(this);

      $('a', link).click(function() {
        var oldCurrentItem = target.find('.active');
        var currentItem = $($(this).attr('href'));
        if(!currentItem.hasClass('active') && !sliding) {
          sliding = true;
          menu.find('li').removeClass('active');
          link.addClass('active');

          currentItem
            .addClass('active')
            .css({'top':settings.height+'px', 'display':'block'})
            .animate({top: 0}, settings.speed);
          oldCurrentItem
            .removeClass('active')
            .css('top', 0)
            .animate({top: -settings.height}, settings.speed, function() {
              $(this).css('display', 'none');
              sliding = false;
            });
        }

        return false;
      });
    })
  }
})(jQuery);

and this can be applied to our markup with:

jQuery(function($) { $("#slideme").anchorize(); });

It’s quite easy to create a jQuery plugin following some simple rules, as we just saw. This plugin can be easily customized adding some new effects, like changing the background, adding borders and so on.

Check out our next tutorials, and have fun with jQuery coding…

Related News