How to Build a Content Slider jQuery Plugin
videos

How to Build a Simple Content Slider jQuery Plugin

I was recently asked by a reader to recommend a helpful content slider plugin. No doubt, there are a bunch of excellent options available — some which are, perhaps, too excellent! With so much flexibility comes extra weight; especially when sometimes you only need a simple slide or fade transition.

So I figured, why not build a simple custom plugin that will get the job done?


Other Viewing Options

P.S. Speed Up

Don’t forget to take advantage of bundles when working in Textmate. If you need a helpful snippet to jump-start every new jQuery plugin, create a new snippet in Textmate, paste the following code in, and then assign a short-cut – like “jqueryplugin.”

(function(\$) {
	
	\$.fn.$1 = function(options) {

		var defaults = {
			$2
		},

		options = \$.extend(defaults, options);
	
		this.each(function() {
		
			var \$this = \$(this);		
			
			$3

            return this;
		
		}); // end each
	
	}
	
})(jQuery);

Conclusion

This is the only the first step. In the next screencast, we’ll continue refining this plugin, and adding more options/conveniences.

Thank you, Screencast.com!


Screencast.com

…for providing the hosting for these video tutorials.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Christophor S. Wilson

    I’m First, Very Nice Tut!

  • http://11heavens.com/ Caroline Schnapp

    I really like where this is is going.

  • http://valendesigns.com Derek Herman

    Jeff, the video is gigantic and over taking the sidebar, can you please fix the width so it looks like it belongs there?

    • http://valendesigns.com Derek Herman

      Looks like you beat me to it! By the time I replied it was fixed, you’re awesome.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Hey Derek – You must have loaded the page within a moment of an update. :)

  • Evan Jones

    Man, I never get tired of sliders. Especially when the holidays are coming up quickly :D Nice choice of images.

  • Los Diggity

    Nice Flex video player. Any chance of getting a tutorial on that? Thanks Tuts!

  • David Ferguson

    Lol this looks vaguely familiar JW :)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      You had some interesting ideas that I learned from. :) But we’ll be doing a lot more with this one and the follow-up screencast.

      • David Ferguson

        I actually made a crossfade plugin screencast right after the contest ended ha. One thing I can say that I did a little different in respect to the fading, was instead of using the css function to adjust the opacity, I used the jQuery fadeTo function. Also, instead of removing and appending the items fo the fade, I did:

        1. Grab first item
        2. Grab next sibling, set z-index to just below the top one
        3. Fade the top, then adjust its z-index to lower.
        4. Set the now top item to very top z-index, and set it to the new top
        5. Loop

        I uploaded it to Blip.tv and it’s had a whopping, 0 views :)

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Do you have a link for us to watch?

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        I’m curious to see more exactly how you worked around the z-index issue – as I’m pretty sure that my way is too intensive and probably unnecessary.

      • dave

        David Ferguson’s
        Creating a jQuery Crossfade Plugin
        http://blip.tv/file/2717716/

      • David Ferguson

        This is more of what I was talking about. I sent an email to you as well with the actual source code file but I figured I would share a link here as well in case anyone else wanted it.

        http://snipplr.com/view/22241/jquery-crossfade-plugin/

      • icetrix

        A follow up? Awesome!

  • http://www.bittrack.it/ Raspo

    A new screencast from Jeffrey Way!

    This will be high-quality stuff like always…
    …let me see…

  • http://bryceroney.com Bryce

    What program did you use to record the Screencast?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Camtasia Studio.

      • Rhonda

        More questions on making the screencast, if you have a moment.

        What screen resolution do you use when you record?
        What size is the area of the screen you record?
        What output size do you use when you publish?

        Could you do a video of how you setup, record, and publish your screencasts that includes that information?

  • http://www.designfollow.com designfollow

    thanks for this great post

  • Jack Franklin

    Great stuff as always – one thing I don’t get is why you use appendTo in the slide method?

  • http://www.webmasterdubai.com webmasterdubai

    really nice plugin good post

  • http://www.kalvster.com Kalvster

    This seems useful for future designs. Thank you!

  • http://ronnieblogg.com Roaa

    Awesome tutorial Jeffrey Way :) i was thinking about this yesterday. Mind reading c”,)

  • http://spotdex.com David Moreen

    Really nice to see a new video if the week. I’m been having lots of fun going back and attempting to do some of the really old ones.

    Not to mention that this tutorial is great, I still have yet to learn how to create a slider from scratch. This takes me one step closer.

  • MasterGates

    This tut will be a great addition to a site I’m working on :D

  • http://www.mexzhouse.com max li bin

    thanks for the tut

  • nadeem

    Thanks, was waiting for this kind of stuff.

  • Stoian Kirov

    Great! I was waiting for that tutorial!
    Thanks Jeffrey :)

  • http://www.ngfusion.com Joris

    Really nice but is there a way to add buttons from 1-5 ?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      That’ll be in the next screencast. :)

  • Greg

    Fantastic tutorial, and I’ve passed it around to staff here in our office. One question: can the images be hyperlinked so, if the user clicks on one, it takes them to an assigned URL? What would the code for that look like?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Sure – in your html, just wrap each image with an anchor tag.

  • Max

    Thank you JW, our screencasts are a must. When I see your name in rss reader -> jump over to the site and check it out.

  • http://shaneparkerphoto.com Shane Parker

    Jeffrey, I too am interested in the player you used for the screencast. Is this one you built, or one you’ve found/purchased somewhere? It’s a nice player! (flex?)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      It’s just the default player that comes with your screencast.com account.

  • Byron McCollum

    Not a full blown plugin, but eliminates the need to to deal with z-index stacking order.

    $(document).ready(function() {

    $.fn.reverse = [].reverse;

    $(‘ul’).each(function() {

    // Reverse DOM Order, Last Is Always Highest
    var list = $(this);
    var items = list.find(‘li’);
    items.reverse();
    list.html(items);

    setInterval(function() {
    list.find(‘:last-child’).fadeTo(1000, 0, function() {
    // Move To First, Reset Opacity
    $(this).prependTo(list).css(‘opacity’, 1);
    });
    }, 5000);
    });

    });

  • http://os.laroouse.com esranull

    ooo thanks example jquery http://os.laroouse.com/category/jquery/

  • Rasmus

    Where did the Twilight theme in TextMate go? :-( I liked it so much.
    Thanks for yet another useful screencast JW.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Just removed it for the screencasts. I still use it. :)

  • http://tutsvalley.com Slobodan Kustrimovic

    Great screencast Jeffrey.

    I have a suggestion considering the little speed VS pause issue.

    Pause should actually be time between 2 animations, and as it is now it actually starts the “pause” when an animation starts (and not when it ends, as it should be)

    So…

    pause += speed

    That way we will actually have a real pause between animations and there will be no need for that little hack of yours :)

    Regards,
    Slobodan Kustrimovic – Boba
    TutsValley

  • Kevin

    Not so pretty on Firefox 2.0 / Ubunto

  • http://orangecoat.com Rick Harris

    Great Tutorial! I find myself building sliders pretty often, and for some reason I’ve never thought of going ahead a building my own jQuery plugin.

    I noticed that in the demo, the “slide-wrap” element was only getting styled inside the “slide” if statement, and therefore wasn’t getting styled at all in the absence of a slider that used the “slide” transition.

    I came up with a solution where that block of code is moved out of the “if” statement and placed below the “wrap” function. Here’s the changes I made:


    // Wrap "this" in a div with a class of "slider-wrap."
    $this.wrap('');

    $this.parent().css({
    'width' : $this.attr('offsetWidth'),
    'height' : $this.children().height(),
    'overflow' : 'hidden',
    'margin' : $this.css('margin-top') + ' ' + $this.css('margin-right') + ' ' + $this.css('margin-bottom') + ' ' + $this.css('margin-left')
    });

    // Set the width to a really high number. Adjusting the "left" css values, so need to set positioning.
    $this.css({
    'width' : '99999px',
    'height' : $this.children().height(),
    'position' : 'relative',
    'padding' : 0,
    'margin' : 0
    });

    The “offsetWidth” attribute was used in place of the width() function because Firefox was calculating the width of the li elements as only 585px because of the scrollbars that appeared because of the overflow: auto in the demo css.

    The height is set to make sure that the containers fully contain their absolutely positioned children.

    I also targeted the “slider-wrap” by using $this.parent() rather than $(“.slider-wrap”) because the latter would effect every slider-wrap on the page (this is why the original problem wasn’t overtly obvious on the demo page).

    Hope this is helpful, and not too painfully long of a comment!

  • http://dreadfullyposh.com jeremy

    Great tutorial Jeffrey! I’ve always hated using some of the giant kitchen-sink-type slider plugins out there, because of how much they lock you into their specific css/html structure requirements. It’s very helpful to understand more about how the effect is being created.

  • Aditu

    Dear Jeffrey,

    is it possible using jQuery to get some html using XHR and filter it using jQuery selectors BEFORE placing into DOM structure? Is it possible to use jQuery traversing/selecting with HTML that is not part of the document (ie. HTML stored in variable)?

    I’m making lots of XHRs to the server and i selects a few pieces of information from the results of these XHRs. Then i use those pieces to update statistics that are on the webpage. It is worth mentioning that i do not control the server with pages I request and use to update stats.

    I was thinking I could inject every result into DOM of my page (and work with it using jQuery) but i believe that loading it into DOM would really slow things down (and also images would be automatically loaded and bandwidth would be another waste). Are there any other convenient ways (other than regexp) to select (filter) pieces of information from HTML received as the result of XHR? Is it possible to use jQuery with HTML that is not part of the document?

  • http://netanius.com N3T@N1U$

    Great Tutorial! tanks
    ;*)

  • Ali Baba

    Hey Jeffrey
    Thanks for tut.

    When we will see next CodeIgniter tut?

    • http://tutsvalley.com Slobodan Kustrimovic

      Same question here :)

  • Stever

    Is there a best way to load multiple javascript jquery files so it more efficient?

  • Nicolas BUI

    Nice tut for people who want to write their own slider !
    I actually use tabswitch plugins as it’s flexible enough and fit my needs .

  • Nicolas BUI

    @Stever : the best way to do so is to merge into one file all scripts in order you need.

  • ryan

    I am having a problem using the plugin, because it is picking up the list item of my horizontal menubar in wordpress, and scrolling it as well. Is there a way to specify in the code the list or a div you want to apply the plugin to instead of the entire page?

  • http://www.szul.eu Pozycjonowanie Olsztyn

    Very nice tutorial :)

  • icetrix

    Really, really awesome. I finally found out how to make a slider, and it is pretty simple.

    Thanks for the screencast!v

  • http://www.jasonbobich.com Jason Bobich

    Jeffrey,

    I’m a huge fan and I’ve learned so much from your screencasts, being a tutsplus member and hanging out on Nettuts.

    Like many, I’ve been experimenting with developing WordPress themes for Themeforest and I have to say that javascript is by far my weakest asset.

    Are we allowed to use this tutorial as a base for creating a content slider for a WordPress theme on Themeforest? Or does that violated copyright issues?

  • Patrick

    It’s not working with I.E. version 7.0

    Is there a fix for it? The images do not fade in and out. It simply is “cuts” to the next image.

  • Zolika

    Decrementing the zIndex isn’t such a good idea…. what happens with negative numbers, or when U reach the smallest negative number? A switch would work everytime. (Also U don’t need two variables in the for loop).

  • Morgan

    How would I change it so it only does one iteration of the loop?

  • http://www.prwebandprint.com Buck

    Hi,
    Great slider I am trying to use in Dotnetnuke, I only want to see first images i.e only the UL but when I remove the second slider the image width expands to all of the images but shows only the slide. How could I fix this so that it only shows the first image width.

  • http://www.beshoydesigns.com Beshoy William

    Hi PLease provide for me any Information about what i am going to ask, i am using IE 8 and when i used this Plugin, it is not working right, but on safari and Google Chrome it works 100 %
    this is the link for what i am talking about
    http://www.al-marzok.com/raccoon/1.html
    Open it in IE
    and On any other Browser

  • alex
  • Thomas M.

    Hey man, UNREAL Tut!

    one questions that I can seem to figure out…on the slider transition, how would you get rid of the pause so it just slowly scrolls through without stopping?

  • http://www.maughan.net.au Ryan Maughan

    Instead of:

    if(options.pause <= options.speed) options.pause = options.speed + 100;

    You can still make the pause work. I found out that the pause starts timing at the same time as the speed. So to account for this, I added the speed time to the pause. Seems to work great!

    options.pause = options.speed + options.pause;

    Anyways, awesome tutorial!

  • Brandon

    Ryan asks a good question. How do I style this so that the rest of my unordered lists (ul) do not freak out when I try to add the slider onto my page?

  • ric

    The plug-in is very nice but when i use this code on my webpage the top menù hide!

    Also the top menù bar is defined with tags.

    What’s wrong?

    IE8 block this script i must allow manually…

  • http://tpmcafe.talkingpointsmemo.com/talk/blogs/john_lennon John

    Hello
    I be struck beside a dreadfully protracted formerly looking directly to the the score that word about this albuterol sulfate, but I can not disinter anyone who can repair me?