412

How can I have a div go from collapsed to expanded (and vice versa), but do so from right to left?

Most everything I see out there is always left to right.

3

17 Answers 17

395
$("#slide").animate({width:'toggle'},350);

Reference: https://api.jquery.com/animate/

7
  • You may also add paddingLeft: 'toggle', paddingRight: 'toggle' when element has internal padding.
    – piotr_cz
    May 6, 2016 at 13:07
  • 19
    Works fine, only it slides from left to right when I try it. Is it possible to make it animate the other way around?
    – twan
    May 20, 2016 at 8:50
  • 2
    The only trouble is that if there is content inside, it "squashes" it horizontally, causing controls to move about/resize/wrap etc. Is there a good solution for that? May 15, 2017 at 22:51
  • 1
    Your code need more CSS to look like a real slide left
    – AmerllicA
    Sep 23, 2017 at 7:03
  • 1
    @NeilBarnwell if you can, put the contents in a wrapper of fixed width and have the container's overflow: hidden. Oct 12, 2018 at 8:03
252

This can be achieved natively using the jQueryUI hide/show methods. Eg.

    // To slide something leftwards into view,
    // with a delay of 1000 msec
    $("div").click(function () {
          $(this).show("slide", { direction: "left" }, 1000);
    });

Reference: http://docs.jquery.com/UI/Effects/Slide

5
  • 155
    @ekerner - this requires JQueryUI, which is a massive library. If all you want is a simple slide transition, this is probably not the answer ;)
    – Jesse
    Nov 10, 2012 at 2:28
  • 11
    This is the best way if you have jQueryUI installed. Nov 14, 2012 at 15:39
  • 5
    To clarify - the min file is at least 235kb!! This is good but it will add considerably to your page as @Jesse points out
    – Ukuser32
    Feb 23, 2016 at 16:24
  • 1
    Using the custom builder and removing everything but the slide animation, it's possible to get the minified JS under 20KB. Jun 29, 2017 at 0:24
  • I wish the JQuery UI docs would have examples like this. Thanks
    – andreszs
    Apr 7, 2018 at 23:27
77

Use this:

$('#pollSlider-button').animate({"margin-right": '+=200'});

Live demo

Improved version

Some code has been added to the demo, to prevent double margin on double click: http://jsfiddle.net/XNnHC/942/

Use it with easing ;)

http://jsfiddle.net/XNnHC/1591/

  • Extra JavaScript codes removed.

  • Class names & some CSS codes changed

  • Added feature to find if is expanded or collapsed

  • Changed whether use easing effect or not

  • Changed animation speed

http://jsfiddle.net/XNnHC/1808/

3
  • 2
    Calculates values in 'px', so not feasible for '%' Jul 28, 2015 at 8:01
  • it is moving to left on every click.
    – Elyor
    Sep 5, 2015 at 17:17
  • You could check outer width and use that to add the right margin
    – Tofandel
    Oct 10, 2019 at 20:11
23

Take a look at this working example on Fiddle, which uses jQuery UI. It is a solution I've used originally from left to right, but I've changed it to work from right to left.

It allows user to click on links quickly without breaking the animation among the available panels.

The JavaScript code is simple:

$(document).ready(function(){
    // Mostra e nascondi view-news
    var active = "europa-view";
    $('a.view-list-item').click(function () {
        var divname= this.name;
        $("#"+active ).hide("slide", { direction: "right" }, 1200);
        $("#"+divname).delay(400).show("slide", { direction: "right" }, 1200);
        active = divname;
    });
});

Get HTML and CSS at the Fiddle link.

Added white background and left-padding just for better effect presentation.

1
19

Use This

<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
<script>
    $(document).ready(function(){
        $("#flip").click(function () {
            $("#left_panel").toggle("slide", { direction: "left" }, 1000);
        });
    });
</script>
1
11
$(function() {
  $('.button').click(function() {
    $(this).toggleClass('active');
    $('.yourclass').toggle("slide", {direction: "right"}, 1000);
  });
});
1
  • 11
    I'm all for comments but this code is pretty self-explanatory.
    – Jon
    Jul 11, 2017 at 23:21
9

or you can use

$('#myDiv').toggle("slide:right");
6
  • 5
    When answering a ten year old question with fourteen other existing answers it would help to explain what new approach your answer brings, and if it would have been valid when the question was asked, or if it is using techniques that became available during those ten years. Aug 28, 2019 at 3:56
  • @JasonAller Why is that? Oct 29, 2020 at 5:12
  • 1
    @groovenectar the answer to that is a long essay that won't fit here and would be off topic here. I suggest you ask this on meta where a full discussion can take place. Oct 29, 2020 at 15:28
  • 2
    @JasonAller, new responses to old questions are very often the most valuable. So I hope people keep doing it without discouragement from participating on StackExchange. Because of the value to doing that, an approach should be an update to SE, e.g. republishing a question with moderator assistance, etc... Some kind of blessing on the practice of answering old questions, rather than discouraging users from posting useful answers... Oct 30, 2020 at 16:07
  • 1
    @groovenectar please show me where in my comment I discouraged adding a new answer to an older question? A code only answer dropped on an older question isn't as useful as one that has both code and explanation. Oct 30, 2020 at 16:12
7

I've done it this way:

var btn_width = btn.width();
btn.width(0);
btn.show().animate({width: btn_width}, {duration: 500});

Note, that node "btn" should be hidden before animation, and you might also need to set "position: absolute" to it.

1
  • Why not use width: 'toggle'? btn.show().animate({width: 'toggle'}, {duration: 500}); is all you would need, I believe. May 12, 2015 at 9:58
7

Another worth mentioning library is animate.css. It works great with jQuery, and you can do a lot of interesting animations simply by toggling CSS classs.

Like..

$("#slide").toggle().toggleClass('animated bounceInLeft');

0
5

GreenSock Animation Platform (GSAP) with TweenLite / TweenMax provides much smoother transitions with far greater customization than jQuery or CSS3 transitions. In order to animate CSS properties with TweenLite / TweenMax, you'll also need their plugin called "CSSPlugin". TweenMax includes this automatically.

First, load the TweenMax library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>

Or the lightweight version, TweenLite:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/easing/EasePack.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenLite.min.js"></script>

Then, call your animation:

 var myObj= document.getElementById("myDiv");

// Syntax: (target, speed, {distance, ease})
 TweenLite.to(myObj, .7, { x: 500, ease: Power3.easeOut});

You can also call it with an ID selector:

 TweenLite.to("#myID", .7, { x: 500, ease: Power3.easeOut});

If you have jQuery loaded, you can use more advanced broad selectors, like all elements containing a specific class:

 // This will parse the selectors using jQuery's engine.
TweenLite.to(".myClass", .7, { x: 500, ease: Power3.easeOut});

For full details, see: TweenLite Documentation

According to their website: "TweenLite is an extremely fast, lightweight, and flexible animation tool that serves as the foundation of the GreenSock Animation Platform (GSAP)."

5

An example of right to left animation without jQuery UI, just with jQuery (any version, see https://api.jquery.com/animate/).

$(document).ready(function() {
  var contentLastMarginLeft = 0;
  $(".wrap").click(function() {
    var box = $(".content");
    var newValue = contentLastMarginLeft;
    contentLastMarginLeft = box.css("margin-left");
    box.animate({
      "margin-left": newValue
    }, 500);
  });
});
.wrap {
  background-color: #999;
  width: 200px;
  overflow: hidden;
}
.content {
  width: 100%;
  margin-left: 100%;
  background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  click here
  <div class="content">
    I would like to have a div go from collapsed to expanded (and vice versa), but do so from right to left. Most everything I see out there is always left to right.
  </div>
</div>

4

You can define first the width of the element as 0, floating right, and then on the event that you are about to show it.. it would be like

$('#the_element_to_slide_from_right_left').animate({ width:'your desired width' }, 600);

Simple as that.

4

Check the example here.

$("#slider").animate({width:'toggle'});

https://jsfiddle.net/q1pdgn96/2/

1
2

An example done by me using the scroll (just HTML, CSS and JS, just with the jquery library). When scrolls down a button will slide left.

Also, I suggest you if the only one that you want is this effect, don't use jQuery UI because it's too heavy(if you just want to use it for that).

$(window).scroll(function(){
  if ($(this).scrollTop() > 100) {
          event.preventDefault();
          $(".scrollToTop").css({'transform': 'translate(0px, 0px)'});
      } else {
          $(".scrollToTop").css({'transform': 'translate(40px, 0px)'});
      }
  });

Check this example

1
  • 2
    Yep, CSS transitions are among the best way to achieve this nowadays.
    – Tom Tom
    Dec 22, 2017 at 10:59
1

If your div is absolutely positioned and you know the width, you can just use:

#myDiv{
position:absolute;
left: 0;
width: 200px;
}

$('#myDiv').animate({left:'-200'},1000);

Which will slide it off screen.

Alternatively, you could wrap it a container div

#myContainer{
position:relative;
width: 200px;
overflow: hidden;
}

#myDiv{
position:absolute;
top: 0;
left: 0;
width: 200px;
}

<div id="myContainer">

<div id="myDiv">Wheee!</div>

</div>

$('#myDiv').animate({left:'-200'},1000);
0

I ran into a similar problem while trying to code a menu for small screen sizes. The solution I went with was to just shov it off the viewport.

I made this using SASS and JQuery (No JQuery UI), but this could all be achieved in native JS and CSS.

https://codepen.io/maxbethke/pen/oNzMLRa

var menuOpen = false

var init = () => {
    $(".menu__toggle, .menu__blackout").on("click", menuToggle)
}

var menuToggle = () => {
    console.log("Menu:Toggle");
    $(".menu__blackout").fadeToggle();

    if(menuOpen) { // close menu
        $(".menu__collapse").css({
            left: "-80vw",
            right: "100vw"
        });
    } else { // open menu
        $(".menu__collapse").css({
            left: "0",
            right: "20vw"
        });
    }

    menuOpen = !menuOpen;
}

$(document).ready(init);
.menu__toggle {
    position: absolute;
    right: 0;
    z-index: 1;
}

.menu__blackout {
  display: none;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.menu__collapse {
  position: absolute;
  top: 0;
  right: 100vw;
  bottom: 0;
  left: -80vw;
  background: white;
  -webkit-transition: ease-in-out all 1s;
  transition: ease-in-out all 1s;
  z-index: 11;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="menu__toggle">Toggle menu</button>

<menu class="menu">
  <div class="menu__blackout"></div>
  <div class="menu__collapse">
    <ul class="list">
      <li class="list__item">
        <a class="list__item__link" href="#section1">Menu Item 1</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section2">Menu Item 2</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section3">Menu Item 3</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section4">Menu Item 4</a>
      </li>
      <li class="list__item">
        <a class="list__item__link" href="#section5">Menu Item 5</a>
      </li>
    </ul>
  </div>
</menu>

0

js:

    $(document).on('click','a.slideleft', function(){
        $('div.slidingdiv').addClass("ml-1000");    
    });
    
    $(document).on('click','.back', function(){
        $('div.slidingdiv').removeClass("ml-1000");
    });
   

html:

    <a class="open">slideleft</a>
    <a class="back">back</a>
    <div>Here on
        <div class="slidingdiv">
           Here off
    
        </div>
    </div>
    
    

style:

    div.slidingdiv{
        position:absolute;
        transition: all 0.2s linear;
        top:0;
        left:0;
        display:inline-block;
        width:100%;
        height:100%;
    }
    .ml-1000{
        margin-left:1000px;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.