Yoda
Yoda

Reputation: 121

Animate divs horizontal to vertical

Alright so here's the deal right now I have div's with a fixed height of 182 x 182 pixels that float left so they align horizontially. What I need to happen is once one of the these divs has been clicked I need all of them to animate from horizontal to vertical if possible. If you can point me to s simple plugin or write the code that would be awesome thanks!

Example:

|-------| |-------| |-------| 
|   1   | |   2   | |   3   | <-- Box 1 is clicked, boxes 2 and 3 need to 
|_______| |_______| |_______|     be animated vertically don't necessarily  
              |                   have to move in straight lines they can
|-------|     V         |         float over or on top of eachother as long as
|   2   |   <--         |         they animate from horizontal to vertical.
|_______|               |
                        |
|-------|               V
|   3   |      <----
|_______|

Upvotes: 1

Views: 1292

Answers (1)

JustAPoring
JustAPoring

Reputation: 258

I always enjoy writing scripts like this. JSFiddle is currently having quite some problems, so have codepen instead:

http://codepen.io/anon/pen/yIhDK

And the code for future preservation

HTML:

<div id="boxcontainer">
  <div class="box box1"></div>
  <div class="box box2"></div> 
  <div class="box box3"></div>
</div>

CSS:

#boxcontainer {
  position: relative;
}
.box {
  width: 182px;
  height: 182px;
  border: 5px solid black;
  margin: 5px;
  float: left;
  position: relative;
}

JS:

$(function(){
  $(".box1").click(function(){
    $(".box").each(function(){
      var width = $(this).outerWidth(true),
          height = $(this).outerHeight(true),
          nrTop = Math.floor($(this).position().top / height),
            nrLeft = Math.floor($(this).position().left / width),
          top = (nrLeft-nrTop)*height,
          left = (nrTop-nrLeft)*width;
      console.log(width, height, nrTop, nrLeft, top, left);
      $(this).animate({
        "top": "+="+top+"px",
        "left": "+="+left+"px"
      }, "slow");
    });
  });
});

The idea behind it is that it calculates for a certain box that it is box n from the left, and puts it positon n from the top. (And vice versa)

Upvotes: 5

Related Questions