417

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.

rmontgomery429
  • 14,660
  • 17
  • 61
  • 66

17 Answers17

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

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

mark.monteiro
  • 2,609
  • 2
  • 33
  • 38
JQGeek
  • 4,055
  • 1
  • 15
  • 2
254

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

EnGassa
  • 2,927
  • 1
  • 14
  • 16
  • 156
    @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 '12 at 02:28
  • 11
    This is the best way if you have jQueryUI installed. – steampowered Nov 14 '12 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 '16 at 16:24
  • 1
    Using the [custom builder](http://jqueryui.com/download/#!version=1.12.1&themeParams=none&components=000000000000000000000000000000001000001000000010) and removing everything but the slide animation, it's possible to get the minified JS under 20KB. – Skylar Ittner Jun 29 '17 at 00:24
  • I wish the JQuery UI docs would have examples like this. Thanks – andreszs Apr 07 '18 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/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
h0mayun
  • 3,466
  • 31
  • 40
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Erwin Julius
  • 519
  • 5
  • 13
20

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>
Shwet
  • 1,848
  • 1
  • 24
  • 35
  • 8
    Yes, you need jQuery UI [for the extended easing options](http://stackoverflow.com/a/12592301/2266583) – zanderwar Oct 28 '16 at 12:07
11
$(function() {
  $('.button').click(function() {
    $(this).toggleClass('active');
    $('.yourclass').toggle("slide", {direction: "right"}, 1000);
  });
});
Hil
  • 329
  • 4
  • 10
9

or you can use

$('#myDiv').toggle("slide:right");
6563cc10d2
  • 193
  • 1
  • 2
  • 8
  • 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. – Jason Aller Aug 28 '19 at 03:56
  • @JasonAller Why is that? – groovenectar Oct 29 '20 at 05: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. – Jason Aller Oct 29 '20 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... – groovenectar Oct 30 '20 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. – Jason Aller Oct 30 '20 at 16:12
  • @JasonAller If your problem is the fact that he has no explaination then point that out. You're complaining about the question being ten years old and having fourteen other existing questions. Either you're giving useless information in your comment, or you're trying to discourage the person indirectly by pointing out these facts. Also: Comments are used to ask for clarification. groovenectar asked for clarification. You could've summarized your answer in one sentence as to why you think it's valuable to point out all the things you said. – I try so hard but I cry harder Feb 18 '22 at 16:40
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.

AbstractVoid
  • 3,583
  • 2
  • 39
  • 39
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');

Soichi Hayashi
  • 3,384
  • 2
  • 22
  • 15
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)."

TetraDev
  • 16,074
  • 6
  • 60
  • 61
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>
fremail
  • 330
  • 4
  • 8
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.

Teody C. Seguin
  • 238
  • 1
  • 8
4

Check the example here.

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

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

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

Jordi Vicens
  • 696
  • 7
  • 17
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);
Colin R. Turner
  • 1,323
  • 15
  • 24
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>
DumperJumper
  • 75
  • 11
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;
    }
Hakan
  • 240
  • 3
  • 4