Web Developer Post

Views: 70561 Comments: 36

Create your own sliding divs with jQuery

Saturday, January 08, 2011

You will often see sliding containers on websites. Many times, developers use these for banner ads, photo galleries, etc. In this article, I'll show you how you can create these yourself using some simple jQuery and CSS without the need of 3rd party plugins.

Demo:

Slide 1

THIS IS SLIDE 1

This is the description that I put for slide one. You can use any html elements or put anything you wish in these containers.

Slide 2

THIS IS SLIDE 2

This is the description that I put for slide two. You can use any html elements or put anything you wish in these containers.

Slide 3

THIS IS SLIDE 3

This is the description that I put for slide three. You can use any html elements or put anything you wish in these containers.

Previous SlideNext Slide

 

 

In order to create this, we'll use a combination of jQuery, xHtml & CSS. So lets start with the layout of the HTML:

HTML:

<!--- DISPLAY CONTAINER --->
    <div id="container">
        <!-- OUTTER WRAPPER -->
        <div id="slider-wrapper">
            <!-- SLIDE 1 -->
            <div id="slide1" class="slide">
                <img src="/Uploaded_Images/jquery-sliding-div-1.jpg" alt="Slide 1" style="float: left;
                    margin-right: 20px;" />
                <h2>
                    THIS IS SLIDE 1</h2>
                <p>
                    This is the description that I put for slide one. You can use any html elements
                    or put anything you wish in these containers.
                </p>
            </div>
            <!-- SLIDE 2 -->
            <div id="slide2" class="slide">
                <img src="/Uploaded_Images/jquery-sliding-div-2.jpg" alt="Slide 2" style="float: left;
                    margin-right: 20px;" />
                <h2>
                    THIS IS SLIDE 2</h2>
                <p>
                    This is the description that I put for slide two. You can use any html elements
                    or put anything you wish in these containers.
                </p>
            </div>
            <!-- SLIDE 3 -->
            <div id="slide3" class="slide">
                <img src="/Uploaded_Images/jquery-sliding-div-3.jpg" alt="Slide 3" style="float: left;
                    margin-right: 20px;" />
                <h2>
                    THIS IS SLIDE 3</h2>
                <p>
                    This is the description that I put for slide three. You can use any html elements
                    or put anything you wish in these containers.
                </p>
            </div>
        </div>
    </div>
    <!--- NAVIGATION BUTTONS -->
    <a href="javascript:void(0)" onclick="PreviousSlide()" id="PreviousButton" style="margin-right: 10px;">
        Previous Slide</a><a href="javascript:void(0)" onclick="NextSlide()" id="NextButton">Next
            Slide</a>

You'll see that there is a div with an id of "container" this is going to be the display area for the slides. Then we have another div with the id "slider-wrapper" this is the div that contains all of our slides. Then within that div, we have multiple divs with ids of "slide1", "slide2" and "slide3", as you may have guessed, these are out actual slides. Now we wont actually use the slide id's for anything but naming purposes. You'll notice that we have assigned a class to these slides called "slide", this is what we will use to style them because we want all slides to have the same properties. Inside of these slides, you can put anything you want including HTML tags. So lets take a look at the CSS setup.

 

CSS:

/* THIS IS THE ACTUAL DISPLAY AREA OF THE SLIDERS */
#container
{
    width: 550px;
    overflow: hidden;
}

/* SET TO THE TOTAL WIDTH OF ALL DIVS */
#slider-wrapper
{
    width: 1650px;
}

/* THESE ARE THE INDIVIDUAL SLIDE PROPERTIES */
.slide
{
    width: 550px;
    height: 200px;
    overflow: hidden;
    float: left;
}

You'll see that our CSS is very simple. We set the div with the id of "container" to show a width of 550px and to hide anything outside of that width. We have set the div with the id of "slider-wrapper" to a width of all of our slides combined. Finally, we have set the properties to our slides using the class "slide". Notice that the width of the slide class matches the width of the "container" id. Now that we have our CSS setup, let's take a look at the jQuery.

 

jQuery:

    <script type="text/javascript">
        var SlideWidth = 550;
        var SlideSpeed = 500;

        $(document).ready(function () {
            // set the prev and next buttons display
            SetNavigationDisplay();
        });

        function CurrentMargin() {
            // get current margin of slider
            var currentMargin = $("#slider-wrapper").css("margin-left");

            // first page load, margin will be auto, we need to change this to 0
            if (currentMargin == "auto") {
                currentMargin = 0;
            }

            // return the current margin to the function as an integer
            return parseInt(currentMargin);
        }

        function SetNavigationDisplay() {
            // get current margin
            var currentMargin = CurrentMargin();

            // if current margin is at 0, then we are at the beginning, hide previous
            if (currentMargin == 0) {
                $("#PreviousButton").hide();
            }
            else {
                $("#PreviousButton").show();
            }

            // get wrapper width
            var wrapperWidth = $("#slider-wrapper").width();

            // turn current margin into postive number and calculate if we are at last slide, if so, hide next button
            if ((currentMargin * -1) == (wrapperWidth - SlideWidth)) {
                $("#NextButton").hide();
            }
            else {
                $("#NextButton").show();
            }
        }

        function NextSlide() {
            // get the current margin and subtract the slide width
            var newMargin = CurrentMargin() - SlideWidth;

            // slide the wrapper to the left to show the next panel at the set speed. Then set the nav display on completion of animation.
            $("#slider-wrapper").animate({ marginLeft: newMargin }, SlideSpeed, function () { SetNavigationDisplay() });
        }

        function PreviousSlide() {
            // get the current margin and subtract the slide width
            var newMargin = CurrentMargin() + SlideWidth;

            // slide the wrapper to the right to show the previous panel at the set speed. Then set the nav display on completion of animation.
            $("#slider-wrapper").animate({ marginLeft: newMargin }, SlideSpeed, function () { SetNavigationDisplay() });
        } 
    </script>

This is where we have a little more code, but not too bad. You'll see at the very top that we have declared two global variables - "SlideWidth" and "SlideSpeed". We also have a function execute when the page is ready as well as 4 additional functions. So lets walk through these together.

The $(document).ready():
In this section we are simply executing the function to set the navigation display buttons. Read further for an exact explination of the function.

The CurrentMargin() Function:
What we are doing here is setting up a function that gets the margin of our "slider-wrapper". The reason we need this is because in order to make the sliding effect, we animate the change of the margin property. This function just simply gets current margin of the div and returns to any function that called it.

The SetNavigationDisplay() Function:
This is the function that turns the previous and next buttons on and off depending on where the slide is. What we do is first check the previous button. You see that we call the CurrentMargin() function to get the margin of the "slider-wrapper". If this margin is 0, then that means we are at the beginning of the slides and to hide the previous button. Next, we check the "slider-wrapper" width and assign it to a variable. We use the currentMargin again with some simple math to determine if the we are on the last slide. If we are, then hide the next button.

The NextSlide() Function:
In this function, we make the animation slide happen. We set a variable called "newMargin" and calculate that by using the CurrentMargin subtracted by the width of a single slide. This will give us the new margin that we need to set our "slider-wrapper" to in order to show the next slide. The next line is the jQuery.Animate() function where we change the "slider-wrapper" margin and animate it at the desired speed. Once the animation has finished, we check the navigation buttons to see if any need to be hidden or shown.

The PreviousSlide() Function:
This function is almost identical to the function above, except this time, we will add the width of an individual slide to the current margin instead of subtracting it. This will allow us to move the slider in the opposite direction.

The last thing is don't forget to include the jQuery library in your page. You should be able to copy and paste this code into your website and it should work perfectly, as long as you have added the jQuery library.


Previous Articles10 most useful jQuery functions for your website
Simple Object Oriented Programming PHP 2 of 2Next Article


Add New Comment

Name:*
Email:*
Website:
What does three added to five make?:
Comment:*
 

Reader Comments

mine didn't work.

where to copy the jquery? is it in the same html or a new file?

nessa

Sunday, January 23, 2011



Hi Nessa,

You need to put the jQuery in the same HTML file. You can put it into an external .js file, but that will require you to put a script reference in the HTML page.

Also, check to be sure that the CSS, if in an external file, is linked properly to HTML page. If you kept the CSS on-page, make sure that you have it wrapped inside of the style tags. Let me know if this solves your problems.

Tony
http://www.webdeveloperpost.com
Sunday, January 23, 2011



Hi there, please forget my last Mail :D
The jQuery Reference was wrong.
But anyway, I have an other question.
Is there a way to implement 2 or more of these sliding divs on one page ??
I'm still working on it, but probably you already have a solution for that !

Thank you !
Alex

Alex

Tuesday, April 26, 2011



Hi Alex,

There is no "simple" way to add another one. The easiest way would be to duplicate the existing code, including the CSS and jQuery and rename the individual ids/classes.

Good Luck!

Tony
http://www.webdeveloperpost.com
Sunday, May 15, 2011



Very simple and elegant solution. Thank you!

Nathan

Sunday, June 19, 2011



i want to start the slider with the slide in the middle
how do i do that?

max

Monday, July 25, 2011



Hi Max,



I haven't tested this, but to make it start on the second slide, just add "NextSlide()" in the document.ready function. So you would change the jquery function to this:



$(document).ready(function () {

// set the prev and next buttons display
SetNavigationDisplay();

NextSlide();

});



Good Luck!

Tony
http://www.webdeveloperpost.com
Monday, July 25, 2011



Hi Tony,

Thank you for your quick response! I just tried that and it works! And it wasn't difficult to code!

thanks again!

max

max

Tuesday, July 26, 2011



Wow.. it is now 2AM and I began searching online for an exact solution that I needed around 8PM. Thank goodness I found this. Exactly what I needed. thanks!

Chris

Sunday, September 25, 2011



thanks for sharing this must-needed knowledge

Yetimwork

Wednesday, October 19, 2011



I copy all the document,and linked them together.

but when I link jquery,the page all disappear.....

why???

chi

Saturday, December 10, 2011



Hi Chi,

You should be able to copy and paste most everything without modification and it will work. Some important things to check is to ensure you are referencing a jQuery file in your head so the jQuery code can execute.

Another thing to check is if you copied the above CSS into the head of your page, you need to wrap it in style tags.

The actual jQuery code I have above that makes everything work can be directly copy and pasted into the head of your page.

Let me know if that works out for you! Good Luck!

Tony
http://www.webdeveloperpost.com
Saturday, December 10, 2011



There are two things that can be problems, depending on what you need this script to do.

If you're using it to display different pages of a form and you tab from field to field, it won't render properly.

Also, if you accidentally click the button again during the animation, it will start the process from its current location and end up off center.

Other than that, it's great.

Dave

Saturday, February 18, 2012



Hello,

How would I make this to scroll automatically and to loop?

Thanks in advance.

Chris

Wednesday, March 14, 2012



I have 10 images in my slide.
I want to add thumbnail, and whenever anyone clicks on that it should take him to that specific slide(image slide).

How can i do that. ?

Please help.

Regards,
Maria

Chiru

Wednesday, March 28, 2012



How would i modify this so that for example: I have three buttons Games, Websites, Other. Each of these are divs that feature most recent work of that type. So instead of having next and previous, just have those buttons assigned to the corresponding div... if you get me...

Frank Clark
franklyinteractive.co.uk
Saturday, May 19, 2012



How can I link to slides directly? So without using the next/previous links, instead linking directly to slides?

For instance a link named Contact should slide to a slide named contact. A link to Home to slide home etc etc? It would be very important and any help would be appreciated!

steve

Thursday, May 24, 2012



Nevermind my question! Got it working:-) Even added some nice features for both directions (Left/Right) and direct linking.

Steve

Thursday, May 24, 2012



Hi. I posted a comment a while ago and would like to try again incase you didn't notice it.

Instead of having previous and next buttons i just want to slide to specific divs. E.g. a div for games, a div for web and a div for other. each with their own links.

I realise i have to delete all the stuff that determines if the next and previous slide buttons should be there. I'm guessing i have to create a function for each link. but i can't quite figure out how it works.

Frank Clark
franklyinteractive.co.uk
Wednesday, May 30, 2012



Steve,
Please share with us the direct linking and stuff you did. I need that and many others too.

Iqtidar
http://3dreaction.blogspot.com
Friday, June 01, 2012



It is very much useful to me.So thanks.

Barun Kumar Jena
baruna@ceptes.com
Saturday, June 23, 2012



Hi, I have to do the slide content more wider and higher. But when I chande values in CSS style the nav buttons disappear. What I should do ? How to do this right way?

Tom

Thursday, July 12, 2012



seems that it is working only with jquery 1.4.2 or below. according to IE8. any ideas about this problem?

joe

Monday, July 16, 2012



Mine isn't working :(
I know that the CSS is linked correctly, and I copied the jQuery inside the header. Everything appears to be correct, but when I click either link, nothing happens...
Help please?
Thank you so much for the elegant code :)

Ashley

Friday, July 20, 2012



I figured out my error! I was incorrectly linking my jQuery library! Now it works as expected. Thank you so much for the beautiful code!

Ashley

Friday, July 20, 2012



Great tutorial! I just wanted to point out a small change that needs to be made. If you continue to click on the arrows quickly then it will move the margin past what the user can see. A fix needs to be included to prevent this. Thanks again for this thorough tutorial!

Oliver

Wednesday, July 25, 2012



I am searching code till midnight but after when I am made myself then I got your code it's good

shobhit

Thursday, July 26, 2012



You have to put that js inside the head tag...

Parthi

Friday, August 03, 2012



I can't use the css background property in it?

Raymond

Friday, August 10, 2012



Nice Work!

Ranjit Singh
http://rsp.site40.net
Thursday, September 06, 2012



hello there! Thank you for this great tutorial, I'm really gratefull.

I have one question though, I want the previous and next link to fade to gray instead of disappearing when they're not needed. I used the css opacity to fade them, but I also need to remove the prev/next fuction assigned to them and then add it again when needed. I've been trying to find a way to do that for several hours, but with no luck, since I ain't a jquery exceprt. I was hoping you could help me with that, I guess the solution is pretty obvious, I just can't see it.

Thanks again!

alex

Friday, September 28, 2012



Hi,

This is very helpful.

But i need some more update for this div slider. Suppose there are two sliding divs,auto start with first div. And after 2 second delay automatically second (Next) div will loaded and No Looping.

Please help me. It is very important to me.

Thanks,
Atiar

Atiar

Sunday, September 30, 2012



I can't seem to get a fourth set of slider tags to work am i missing a parameter for that somewhere?

shell

Thursday, November 08, 2012



Thanx a ton dear

Sarfraz Ahmad

Tuesday, December 04, 2012



I've got this error message: Uncaught ReferenceError: $ is not defined.

victor

Tuesday, December 04, 2012



I've fixed, I'm sorry, I was not watchfully enough! thanks

Victor

Tuesday, December 04, 2012


Most Popular Articles


Recent Articles



© Copyright 2010. WebDeveloperPost.com
Tampa Web Design By Ricketts