Slide Elements in Different Directions

read 62 comments

Although jQuery has a nice set of slide methods — .slideDown(), .slideUp(), and .slideToggle() — sometimes we may want to slide an element in a different direction. Fortunately, it's pretty easy to do.

Reverse the Slide Direction

With the built-in slide methods, elements are shown by sliding them down and into view. But what if we want to slide something from the bottom up and into view? The trick here is to use some judicious CSS. Let's start with a simple HTML structure:

HTML:
  1. <div id="slidebottom" class="slide">
  2.   <button>slide it</button>
  3.   <div class="inner">Slide from bottom</div>
  4. </div>

To get the inner div to slide up, we'll anchor its bottom edge to the bottom of the bottom of the nearest positioned ancestor (in this case, the #slidebottom div):

CSS:
  1. .slide {
  2.   position: relative;
  3. }
  4. .slide .inner {
  5.   position: absolute;
  6.   left: 0;
  7.   bottom: 0;
  8. }

Other properties such as width, padding, margin, and background-color have been set for these elements, but only the essential properties for modifying the slide behavior are shown above.

Note: I'll be using the term positioned to refer to elements that have the CSS position property set to something other than "static." Both divs in this example are positioned — one absolutely and the other relatively.

Now, we can write the jQuery the same way we would with a traditional slide effect:

JavaScript:
  1. $(document).ready(function() {
  2.   $('#slidebottom button').click(function() {
  3.     $(this).next().slideToggle();
  4.   });
  5. });

Try it out:

Slide from bottom

Horizontal Slides

Animate Width

We can also slide elements to the left and right. The simplest way is to animate the element's width property.

JavaScript:
  1. $(document).ready(function() {
  2.   $('#slidewidth button').click(function() {
  3.     $(this).next().animate({width: 'toggle'});
  4.   });
  5. });

In this case it's not necessary for the sliding element to be positioned.

Animate this element's width

While animating the width is fine for what it is, I'm not crazy about how the text wraps as the width decreases. One way to avoid the wrapping is to add a CSS declaration such as white-space: nowrap;, but that would mess up the appearance of an element with a lot of text—one in which we would expect to see text wrapping when it is at full length.

Animate Left

Another way to avoid the text-wrap issue is to animate the element's left property. Here, it's important once again to make sure that the element is positioned. After all, we can't move an element if it's static.

With this animation, we need to calculate how far to move the element. The following code rests on two assumptions: (1) the sliding element has an outerWidth() that is equal to or greater than its parent element's width, and (2) the sliding element is initially set to left: 0;. You may have to adjust your code if either one of these assumptions doesn't hold in your situation.

JavaScript:
  1. $(document).ready(function() {
  2.   $('#slideleft button').click(function() {
  3.     var $lefty = $(this).next();
  4.     $lefty.animate({
  5.       left: parseInt($lefty.css('left'),10) == 0 ?
  6.         -$lefty.outerWidth() :
  7.         0
  8.     });
  9.   });
  10. });

Lines 5 through 7 use a "ternary" operator that basically says, "If the left css property equals 0, move the element to the left as many pixels as it is wide (including padding and border); if not, move it back to 0."

Animate this element's left style property

Also, if we want the element to be hidden when it slides to the left, we need to add overflow: hidden; to its parent element.

Animate Left Margin

Finally, we can achieve the same effect as the left animation by animating the marginLeft property. In this case, we still need overflow: hidden; on the parent element, but the sliding element does not need to be positioned.

JavaScript:
  1. $(document).ready(function() {
  2.   $('#slidemarginleft button').click(function() {
  3.     var $marginLefty = $(this).next();
  4.     $marginLefty.animate({
  5.       marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ?
  6.         $marginLefty.outerWidth() :
  7.         0
  8.     });
  9.   });
  10. });

For the sake of variety, we're sliding this one to the right.

Animate this element's margin-left style property

With a couple little tweaks, these horizontal slides can be used for a horizontal accordion.

Further Resources

comment feed

62 comments

  1. Nice use of the outerwidth() method! ;-) Excellent tut, keep it up!

  2. Great post Karl. Useful tips explained clearly. :)

  3. Awesome post! Was recently trying to do this for a project and figured out everything but the 'slide left' while anchoring the left side. Thanks!

  4. Nordes

    Great post. I will surely use those useful tips.

  5. This is great! A much needed explanation for a horizontal slide solution. Nice work Karl.

  6. It's great to see more posts on real scenarios. This is a truly helpful post for those new to the jQuery library. Great job!

  7. Great tutorial!

    How would I create a slide up/down for multiple divs on a page using a single function to execute any one div slide at a time?

  8. Rob

    Excellent, i was just looking at how to implment a sliding footer. Thanks ;-)

  9. Santo

    Could you provide the whole .js , css, and html files for your examples? I'd like to know all the details . Would be very helpful :)

  10. cool8jay

    How to run javascript and css in wordpress post?
    Using a plugin?
    Can someone tell me? Thanks!

  11. Good Example, nice collection of the sliding direction in one. Thank you

  12. Very good tut, I just knew about your this site and I think it rocks!
    Thanks to share it.

  13. Great stuff. We use JQuery and the various plug ins in our custom monitoring pages. It really makes our job easier.

  14. Wow super Method. ! Veri Good
    One Question:
    What Create PopUp Window?

  15. nice tutorial for a guy like me who just started learning jquery.thanks a lot

  16. Spen

    Hi Karl. Thanks very much for posting these methods. I am particularly happy with the last horizontal slide. I have got it to slide in from the right, but am stuck with the accordion method you mentioned. Any chance of a clue how to implement this please? Cheers!

    • Hi Spen, I'm hoping to write a new tutorial on creating a horizontal accordion within the next couple weeks. Feel free to remind me via email if I forget. ;)

      • Michael

        Is there a reason for vars in the format of $foo... its mildly confusing since the framework uses $ heavily

      • Hi Michael, there is nothing special about the $ in JavaScript, but it has become a convention in jQuery scripts to begin a variable name with it when the variable is referring to a jQuery object.

  17. Karsten

    Hi Karl, I'm a freshman just started learning jquery. Your examples are easy to understand but there is something I don't conceive: In your first example, the "Slide from bottom" the sliding div isn`t visible until you click on the button. This is exactly what I'm looking for!

    My problem is, in all my test with your code the sliding div is visible from the first time. Pleace could you explain why this happen? Thanks for your support! Karsten

  18. Netzi

    Hello. Thank you for this great tutorial. I like the slide in from the left most. But I can't figure out how to start with a hidden div that slides in from the left. All your examples start with a visible div. It would be awesome if you could tell me how I can get this working.

    Regards

    • Hi Netzi,
      If you're using the one that animates the left property, you could do this after line 3:
      $lefty.css('left', -$lefty.outerWidth())

      If you're using the marginLeft one, do this after line 3:
      $marginLefty.css('marginLeft', $marginLefty.outerWidth())

      • Ian

        Hi Karl,

        I couldn't get the jQuery solution to work, the slide effect just went crazy and kept sliding in from the left.

        I fixed it with a - slightly less flexible - CSS solution

        
        #slideleft .inner {
          left:-350px;
        }

        Where the value of the left property is the same as the width of the parent container.

  19. Great tutorial indeed! Now how would i need to alter the code to have the "marginLefty" inner div to be invisible from the get go? And is it possible to alter the content of the hidden DIV with custom html data before sliding it out for overview? Any help will be much and much appreciated!

    Thank you so much!

  20. marshane

    Great post!!

  21. James

    Hi, please could someone let me know how i can use a standard text link instead of a button, and have that text link trigger the slide elsewhere on the site?

    I tried moving the button elsewhere, but it didn't work :(

    thanks for any help

    • its really simple to do so... Instead of the button use an anchor element with ur text in it and give it any id for example:
      use this at any place on ur page:
      Click me to slide the element
      and in the js call use $("#slide-handle").click instead of$("#slidemarginleft button").click
      hope that helps...

      • I couldn't get this to work, and I'm trying to do the same thing.

        The problem is it works great if I'm clicking a button with that certain inner div that I want to hide, but what I want to do is have a MOUSEOVER signal the DIV to fly in/fly-out.

        I've gotten the other method you wrote about, "slick-show" to work this way no problem. But what I really want is the div to come in from the right side when you mouseover a link and I'm frankly too much of a n00b to jQuery to understand how to look at this code and modify it to work. All of my experiments failed :p

  22. cincoutprabu

    The reverse slide (slide from bottom) approach doesnt work for all cases.
    Use the following animation technique to slide from bottom

    To slide-up-from-bottom (show):

    
    $('.inner').show();
    $('.inner').css({ height: '0px' });
    var height = 40; //set slide amount here
    $('.inner').animate({ marginTop: '-' + height + 'px', height: height + 'px' }, 'slow');
    

    To slide-down-from-top (hide):

    
    $('.inner').animate({ marginTop: '0px', height: '0px' }, 'slow', function()
    {
    	$('.inner').hide(); //hide after animation
    });
    

    For more, mail me....

  23. Patrick

    Karl - great post. This is exactly what I'm trying to do with one exception.. How do I slide with a background-image within the sliding div?

    I've it working in all but ie6.. ie6 lags in that I see it trying to redownload the bg image in my status bar even though it's refenced in the CSS. hex colors work fine.

    Thanks for your hard work!

    -P

    • I'm not sure, but could it have something to do with ie6 not caching bg images? I often put something like this in an ie6-only script:

      try {
          document.execCommand( "BackgroundImageCache", false, true );
      } catch( e ) { };
      
  24. This is great!
    I'm trying to use the Animate Left on hover.
    I get the slide out but I can't get my element to slide in again.
    What am I doing wrong?
    This is my code:

    
    $('.contentWrap').hover(function(){
    		var $lefty = $(this).find('.hover_link');
    		$lefty.stop().animate({left:-$lefty.outerWidth()},{queue:false,duration:500});
    	}, function(){
    		$lefty.animate({left:'0'},{queue:false,duration:500});
    	});
    
  25. Marcuss Zilgalvis

    Hey there, this is really good stuff tho ive got some questions.
    Is there any possible way to use the link button outside that div, for example like:

    Animate this element's margin-left style property

    click this button

    And those divs stand next to each other, button div on the right side, so that means i'd like to have the slide to slide in from the right side only when clicked, and not already on page reload.

    Any ideas ? :)
    Much appreciated in advance.

  26. Great tutorial!

    Two things:

    1.) Is it possible to start with the sliding div hidden and then slide left from the right side of the containing div when the toggle button is pressed?

    2.) Is it possible to make the toggle button slide with div? My setup is that there is a rectangular div that slides, but I would like the toggle button to be a 20px tag off the left edge of the sliding div so that it sticks out while the rest of the div is hidden.

    Thanks very much!

    • Brianne C

      Mort –
      I'm trying to achieve the same tab type effect on a site I'm developing. Have you had any success with your code?

      Thanks–
      BC

    • archie

      Hi Mort,
      Have you had any luck with your inquiry?
      Your request is exactly the solution I am looking for.
      Cheers
      Archie

    • Hi Mort (and Brianne and Archie).

      Wanted to let you know that I'm working on a new post that will explain how to do the fly-out menu thing. Should be ready within the next week or so.

      • Archie

        Hi Karl,
        Thanks for responding. How is the post coming?
        I'm sorry to appear so eager but I have been a frustrated 'cut and paste cowboy' all week stumbling around in the jquery darkness.
        Cheers
        Archie

        • Archie, it should be ready within the next week or so (give or take a couple days). In the meantime, take a look at this demo and let me know if it's what you had in mind.

        • archie

          Hi Karl,
          Sorry about my last query, I really did not want to appear impatient I was just excited to find your reply, and relieved by the prospect of finally putting my sliding tab problem to bed.
          The demo you mention is very good but a lot more complex that what I require.
          Ideally I would like a tab containing an arrow image that slides in from the right side of my wrapper div to reveal a 'contact details' div approx 75 px high and 300 px wide. The content I need inside the 'contact details' div is not in the form of an ul but simple para with links.
          I am looking forward to your reply and in the mean time I will try to dissect the demo into something I can use.
          Many thanks,
          Archie

  27. archie

    Excellent effort Karl,
    Thank you for sharing this resource!!!
    I too am looking for the same functions as Mort.
    Do you have any suggestions?
    Cheers
    Archie

  28. Wow very cool! could someone help me with Animate Width version i want to slide that one from right to left and then back from right to left. I kinda like it that you can see the text go smaller while it closes. thanks! gr. bram

  29. lnv

    Hi Karl,
    Thanks for these examples. I am trying to implement your marginleft slide but I need to target a particular div. I can't figure out how to do that with your code. Could you please help? Thanks!

    • lnv

      Got it. If anyone is interested the line to change to target a particular div is:
      var $marginLefty = $(this).next();

      Change it to something like:

      var $marginLefty = $('#yourDivID');

      You will need to change this if your triggering anchor appears AFTER your sliding div in your code.

  30. great post!!

    however, is it possible to have a slide down to hide an already visible item?

    here you start with the item already hidden, then slide it "up" to reveal it. using slideToggle is a natural way to acheive this since it slides up to reveal

    but what if your item is already showing? how would you slide it "down" to hide it?

    thanks!

    • As long as you have the CSS defined correctly (using the bottom property and setting position to relative or absolute), all you need to do is use the .slideUp() method. Just don't hide it initially.

  31. Thanks for the great tip. It worked like a charm.

  32. Cookies anyone? Has anyone here considering how to make this integrated with cookie?

  33. This is great! A much needed explanation for a horizontal slide solution. Nice work

  34. nice post....
    how to make image slide with jquery..?

    bali web programmer

  35. Prathap

    Hi, nice tutorial but can you kindly guide me how to implement an auto slide from left to right.

    when the ul or div content is loaded, at certain time the slide should appear on top with the caption from left to right and disappear for the next slide.

    Thanks( waiting for someone to reply)

  36. Deepak

    Hi Karl,

    Great post . . . thanks a lot.
    I implemented the same thing, but instead of a button to trigger the slide, i have used an image with the onClick event, calling a javascript function to change the image on click . The image shown is to be toggled on every click to indicate the change in direction . . . It works great in firefox... The problem i am facing is that in IE6 , the first time i click the image , the image changes indicating change of direction, but the slide doesnt work. From the second click onwards, the slide starts working fne, but because it failed for the first click, the image shown is each time the opposite of what it needs to be . . . . any idea how this could be fixed.
    I alos used a button instead of an image as you have shown, , and the even the first button click doesnt make it slide . . .

5 Pings

  1. [...] Slide Elements in Different Directions (Karl Swedberg) [...]

  2. [...] Slide Elements in Different Directions » Learning jQuery - Tips, Techniques, Tutorials (tags: tutorial jquery animation) [...]

  3. jQuery - Efeito corrediço em diferentes direções...

    Embora a biblioteca jQuery tenha nativamente seus métodos para obtenção do efeito corrediço — .slideDown(), .slideUp() e .slideToggle() — em algumas ocasiões pode ser necessário criar o efeito em uma direção diferente daquela dispon...

  4. [...] Jquery is truly a heave for Jquery lovers. You can easily learn how to create animations using Jquery and much more advanced Jquery [...]

  5. [...] See the article here: Slide Elements in Different Directions » Learning jQuery – Tips, Techniques, Tutorials [...]

Leave a Comment

IMPORTANT:

  • If you wish to post code examples, please wrap them in <code> tags.
  • Multi-line code should be wrapped in <pre><code> </code></pre>
  • Use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.