How to Create your own jQuery Slider Plugin

How to Create your own jQuery Slider Plugin

50 288535
Own jQuery Slider Plugin
Creating own jQuery plugin - slider

Create your own jQuery plugin – slider

Today we will create own first jQuery plugins. As one of easy task – we will create own image slider (commonly – of any content, not just images). Our slider will switch between slides using the fade effect.

Firstly – you can download our package and check demo:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Lets start coding !


Step 1. HTML

As usual, we start with the HTML. This is source code of our sample:

index.html

<link rel="stylesheet" href="css/main.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<div class="example">
    <h3><a href="#">My Slider example</a></h3>
    <ul id="my_slider">
      <li><img src="data_images/pic1.jpg" alt="" /></li>
      <li><img src="data_images/pic2.jpg" alt="" /></li>
      <li><img src="data_images/pic3.jpg" alt="" /></li>
      <li><img src="data_images/pic4.jpg" alt="" /></li>
      <li><img src="data_images/pic5.jpg" alt="" /></li>
      <li><img src="data_images/pic6.jpg" alt="" /></li>
      <li><img src="data_images/pic7.jpg" alt="" /></li>
      <li><img src="data_images/pic8.jpg" alt="" /></li>
      <li><img src="data_images/pic9.jpg" alt="" /></li>
      <li><img src="data_images/pic10.jpg" alt="" /></li>
    </ul>
    <div id="counter"></div>
</div>

As you can see – all very easy, here are UL-LI structure with slider tabs inside. In end – additional counter element.

Step 2. CSS

Here are used CSS file with styles of our demo:

css/main.css

body{background:#eee;margin:0;padding:0}
.example{background:#FFF;width:500px;border:1px #000 solid;margin:20px auto;padding:15px;-moz-border-radius: 3px;-webkit-border-radius: 3px}
/*My slider styles*/
#my_slider {
    width:500px;
    height:340px;
    overflow: hidden;
    position:relative;
    list-style: none outside none;
    padding:0;
    margin:0;
}
#my_slider li {
    position: absolute;
    top: 0px;
    left: 0px;
    display:none;
}
#my_slider li:first-child {
    display:block;
}
#counter {
    text-align:right;
    font-size:16px;
    width:500px;
}

Step 3. JS

Here are all JS files:

js/main.js

(function($){
    $.fn.MySlider = function(interval) {
        var slides;
        var cnt;
        var amount;
        var i;
        function run() {
            // hiding previous image and showing next
            $(slides[i]).fadeOut(1000);
            i++;
            if (i >= amount) i = 0;
            $(slides[i]).fadeIn(1000);
            // updating counter
            cnt.text(i+1+' / '+amount);
            // loop
            setTimeout(run, interval);
        }
        slides = $('#my_slider').children();
        cnt = $('#counter');
        amount = slides.length;
        i=0;
        // updating counter
        cnt.text(i+1+' / '+amount);
        setTimeout(run, interval);
    };
})(jQuery);
// custom initialization
jQuery(window).load(function() {
    $('.smart_gallery').MySlider(3000);
});

Firstly, make attention to $.fn.MySlider, so it mean that I registering my function as new jQuery function (expanding its functions). Then I made simple switching mechanism between images. And, using fadeOut-fadeIn – perform ‘switching’. So, as result, we can call ‘MySlider’ function for any UL element which we want to use as slider. Example: $(‘.smart_gallery’).MySlider(3000); (where 3000 – delay between switching).

js/jquery-1.5.2.min.js

This is default jQuery library. Available in our package.


Live Demo

Conclusion

Today I told you how to build new own jQuery plugin. Sure that this will useful for you. Our sample result was very easy, and very small. The whole JS code can even be compressed to 284 bytes :) Good luck!

SIMILAR ARTICLES

Polaroid gallery

0 59965
jQuery Mobile Lesson 6

0 20715

50 COMMENTS

  1. Hello! I love this script. Could you please do one more tutorial showing how to add in a caption feature, and next/previous image links? Thank you!

  2. Do you need to call setTimeout(run, interval); twice? Calling it once on line 30 should be enough.

    • You can change
      setTimeout(run, interval);
      to
      run(); at line 30.
      To get a timer to work in an infinite loop, we need write a function that calls itself.

  3. Loved the tutorial. Simple and as the saying goes “simple is most effective”

    I’ve tried this and it will not open up in IE9…

    Any suggestions?

  4. The first image appears in IE9 but the rest don’t seem to work – the first image fades to white and no more appear. It works fine in Firefox and Safari. Please help?

    • Can you tell us version of your IE9? Just because I tried it in my v9.0.8112 right now – and it worked to me. I just waited a little.
      Are you got any warnings in IE?

    • Hi sidharth,
      Shortly – you should add MouseOver event handler, and stop our timer in this moment (pause). Or, you can implement alternative solution with adding some new variable, and, in case when we keep mouse over our slider – set this variable to TRUE (as example), and in our cycle (run function) – check for this variable.

  5. How would I make the pictures in the slider a clickable link? I tried using the image as a link but I ended up with a blank and no picture would display

    • Hello Chris,
      You can try to do clickable images in next way:
      <li><img src="data_images/pic1.jpg" alt="" /></li>
      change to
      <li><a href="your_address"><img src="data_images/pic1.jpg" alt="" /></a></li>
      after, in our JS code we have to change
      slides = $(‘#my_slider’).children();
      to
      slides = $(‘#my_slider li’);

  6. Great tutorial! Just what I was looking for.. One question though. Is it possible to slow the time it transitions to the next slide? Meaning have the slide last longer?

  7. The tutorial is fine, but one small comment is that it isn’t actually a slider. This is more of a “carousel” as the images don’t actually “slide” in and out of view.

    • Interesting suggestion, I thought that a slider is something (object) where we can see replacing each other images, but anyway yes- possible.

  8. This code is very easy to learn slider.
    I want to know how we may use next and prev button in slider

    • Hi Mohd,
      Prev/Next buttons? These buttons were not originally conceived, if you really need them – you will need to implement them with your own hands. An average functionality could be like that: stop timer, switch to next slide, update counter, start timer (optional)

  9. You rock bro. Simply but powerfull. Thanks. But I have a question. How can I make reponsive slider that will auto generate width to any mobile browser?

    • Hi Sepatu,
      I think that you can use an easy responsive rule, like:
      @media (max-width: 1000px){
       img {
        width:98%;
       }
      }

  10. Hi, realy amazing tutorial :)
    How can I do something like switcher? E.g (1 | 2 | 3 | 4 | 5) that can change the slide?

    • Hello Martin,
      In your case, you can try to change the inner ‘i’ variable, depending on what slide you need to display

  11. Hi! really great tutorial but i can’t understand from where (interval) comes!

    // $.fn.MySlider = function(interval)

    it’s declared in jquery??? or what? thanks again

    P.S little hint for your website: install a system that let peoples subscribe post and comments becuase now i don’t know when you’ll answer to me so i’ve to come back and check by myself. :) have a nice day.

    • Hello Stefano,
      Thank you for your valuable hint, .. if you can suggest me a proper plugin (WP), I will add it.
      To answer your question – yes, this is made as a new extension (plugin) for jQuery.

  12. Thanks very much. this was useful, just that am stock here.
    i want to be able to make the sliding purse when someone hovers on it
    and also i need to generate number for the count so one can easily jump to a desired slide.
    can you help pls..

    • Hi SLB,
      If you want to implement the onhover effect to our slider, you will need to stop-start the timer, depending on the ‘onhover’ state.
      If you need to jump to a certain slide, you can just try to change a current slide (inner ‘i’ variable)

  13. Hello sir,

    FIrst i have opened three notepad, then i paste there for html, css and js,, but i am not getting the results, i just can see the pics which i have put in my images folder,,, moreover i download the complete code “source.zip” as you provide,, but still i am not getting the result which is show in the live demo,, i can just see the images there laying vertically…

  14. Question: I applied the slider on my homepage but wanted the slider to adjust as end-users resize the windows. I added “width=100%” to each images. The images does resize but it leave a big space between the slider & the bottom content as I resize the window.

    • Hi Kelly,
      You don’t need to resize images itself, but you have to resize only the parent element (#my_slider). You may set width for ‘my_slider’ = 90%; and width for images: 100%

      • I tried that but still there’s a huge gap in-between the slider & text content on the homepage whenever I resize the window to mobile view. I built this site for desktop & mobile view.

        Source Code:

        /* === Source Code Start === */

        Visualize the body you want right now. Visualization is the language between your mind and body. What you hold in your mind on a consistent basis is exactly what you will experience in life. Be hungry – be unstoppable.

        /* === Source Code End === */

        CSS:

        /* === Desktop Version Start === */

        #my_slider {
        width: 90%;
        height: 365px;
        overflow: hidden;
        position:relative;
        list-style: none outside none;
        padding: 0;
        margin:0;
        }

        #my_slider li {
        width: 100%;
        position: absolute;
        top: 5px;
        left: 0px;
        display:none;
        }

        #my_slider li:first-child {
        display: block;
        }

        /* === Desktop Version End === */

        /* === Mobile Version Start === */

        #my_slider {
        width: 90%;
        height: auto;
        overflow: hidden;
        position: relative;
        list-style: none outside none;
        padding: 0;
        margin: 0;
        }
        #my_slider li {
        width: 100%;
        position: relative;
        top: 0px;
        left: 0px;
        display: none;
        }
        #my_slider li:first-child {
        display: block;
        }

        /* === Mobile Version End === */

        Your help would be greatly appreciated. I love the simplicity of this slider. Thank you in advance.

  15. Hi Kelly,
    I tried your CSS code (Desktop Version), I also added some text before and after the slider. However, there was no any gap between the slider and texts. However, when I tried your Mobile version, it didn’t work good on my computer (there are some problems with styles). If you need my assistance, you may contact me PM, and I might have a look at your online version.

  16. please how do i create an upload function in asp.net c# , so that when i upload images it will appear on the slide on the home page. Please any idea?

  17. Love That :-)
    All was delicious , even reading the comments and dear admin answers , good luck.

    • Hi Sivaram,
      Basically – yes, this is possible. You need to clear timeout (interval) when you keep your mouse over the slider. And when you leave the object – you need to re-‘run’ it

  18. I studied the code for slider, given in three steps seems to be ok. I have special need for HTML 5. Suppose I have a separate image folder and different images are there. One box showing multiple thumb pictures appears in a window and when you click anyone it popup with a bigger size with three lines detail. But, these three lines information should come from the database (MySQL table).

  19. hey Andrey,
    these code is not working at my end even i copied whole code like css, html and script too. all are fine but animation not working

Leave a Reply