Geroy290
Geroy290

Reputation: 478

How to use .animate() to expand width from a specific side

I am trying to animate an opening sequence for a project and am wondering how I can use .animate() to make my div "come in" from the right instead of the left which seems to be the default.

I am sure it is a simple solution, here is my code and fiddle:

JSFiddle

$("#clickMe").click(function() {
    $(".login").animate({width: '0'});
}, function() {
    $(".login").animate({width: '100'});
});

Thanks!

Upvotes: 1

Views: 57

Answers (2)

Jazzman
Jazzman

Reputation: 181

its a simple solution but should be enough for simple cases:

Wrap your login with container with exact width and height:

<div class="wrap">
  <div class="login"></div>
</div>

Than apply styles:

.login {margin-left: 100px; height: 100px; width: 100px; background-color: red;}
.wrap{
  width: 100px;
  height: 100px;
  overflow: hidden;
}

You move your .login to the right side of the .wrap (using margin-left:100px;) and add overflow:hidden to .wrap (.login will be not visibile) than simply reset margin-left to 0 :

$("#clickMe").click(function() {
    $(".login").animate({marginLeft: 0});
}); 

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240928

You could set a margin-left with a value equivalent to the element's width and animate it at the same time. In doing so, the width animation is essentially displaced by the margin.

$("#clickMe").click(function() {
  $(".login").animate({
    'width': '100',
    'margin-left': '0'
  });
});
.login {
  height: 100px;
  width: 0px;
  background-color: #f00;
  margin-left: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickMe">
  Click To Change Size
</button>
<div class="login"></div>


Alternatively, another approach would be to float the element to the right inside of a parent element with the same dimensions:

$("#clickMe").click(function() {
  $(".login").animate({width: '100%'});
});
.animation-wrapper {
  width: 100px;
  height: 100px;
}
.login {
  height: 100%;
  width: 0;
  background-color: #f00;
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickMe">
  Click To Change Size
</button>
<div class="animation-wrapper">
  <div class="login"></div>
</div>

Similarly, you could also just animate the left property and hide the overflow:

$("#clickMe").click(function() {
  $(".login").animate({'left': '0'});
});
.animation-wrapper {
  position: relative;
  height: 100px;
  width: 100px;
  overflow: hidden;
}
.login {
  height: 100%;
  width: 100%;
  background-color: #f00;
  position: absolute;
  left: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickMe">
  Click To Change Size
</button>
<div class="animation-wrapper">
  <div class="login"></div>
</div>

Upvotes: 2

Related Questions