Matt Picca Matt Picca - 1 month ago 6
Javascript Question

Animating a Div with Responsiveness

Just need a little help. I want to animate below box to be responsive to the size of the page using (window).width(); and (window).height();
Where should i implement the (window).width & height function? Here is what I have done so far:

Code:

$(document).ready(function(){
$(".box").click(function(){

run();

});
});

function run(){
var duration=1000;
var width=$(window).width();
var height=$(window).height();
$(".box").animate({"marginLeft":"1000px"},duration,function(){
$(this).animate({"marginTop":"600px"},duration,function(){
$(this).animate({"marginLeft":"0px"},duration,function(){
$(this).animate({"marginTop":"0px"},duration,function(){
run();


});
});
});
});

}


CSS:

.box{border:1px solid black; width:200px; height:200px; float:left;}

Answer

You just need to use your window width and height, the tack out the height and width of the box like this:

$(document).ready(function() {
  $(".box").click(function() {

    run();

  });
});

function run() {
  var duration = 1000;
  var width = $(window).width();
  var height = $(window).height();
  $(".box").animate({
    "marginLeft": width - 200 //<-----
  }, duration, function() {
    $(this).animate({
      "marginTop": height - 200 //<-----
    }, duration, function() {
      $(this).animate({
        "marginLeft": "0px"
      }, duration, function() {
        $(this).animate({
          "marginTop": "0px"
        }, duration, function() {
          run();


        });
      });
    });
  });

}
.box {
  border: 1px solid black;
  width: 200px;
  height: 200px;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">

</div>