Animate image within a div border

Viewed 440

I'm trying to animate an image that should move randomly inside a div container borders. I found few solution here to set the animation border, but non where the image stays inside the div.

I have a snip for example - I need the red square to move inside the yellow div, even if I scroll down the page.

How can I achieve that?

$(document).ready(function() {
    animateDiv();

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    $container = ($container || $(window))
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv() {
    var $target = $('.a');
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv();
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div#container {height:100px;width:100px;margin-left: 500px;background-color: yellow;}

div.a {
width: 50px;
height:50px;
 background-color:red;
position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>

3 Answers

When you give position:absolute; for an element you must define an element with position:relative; so that the child (absolute element) won't go outside its boundary.

$(document).ready(function() {
    animateDiv();

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    $container = ($container || $(window))
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv() {
    var $target = $('.a');
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv();
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div#container {
  height:100px;
  width:100px;
  margin-left: 500px;
  background-color: yellow; 
  position:relative;/*Added position to the parent container*/
}

div.a {
 width: 50px;
 height:50px;
 background-color:red;
 position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>

Reference Link 1: https://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

Live Demo: https://www.w3schools.com/css/tryit.asp?filename=trycss_position_absolute

$(document).ready(function() {
    animateDiv();

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    $container = ($container || $(window))
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv() {
    var $target = $('.a');
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv();
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div#container {
position:relative;
  height:100px;width:100px;margin-left: 500px;background-color: yellow;}

div.a {
 width: 50px;
 height:50px;
 background-color:red;
 position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>

I am using CSS animation to make it look much smoother. Changes are documented in the Javascript/jQuery and CSS source code.

CSS animations are much faster than jQuery animate because they can run on a separate thread.

$(document).ready(function() {
  /* Initiate animation */
  animateDiv();
    
  /* Apply animation class */
  $(".a").addClass("animate");
});

/* Trigger the end of the transition */
$("div.a").on('transitionend', function() {
  /* Run next animation when previous one stopped */
  animateDiv();
});

function makeNewPosition($container) {
  // Get viewport dimensions (remove the dimension of the div)
  $container = ($container || $(window))
  var h = $container.height() - 50;
  var w = $container.width() - 50;
  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);
  return [nh, nw];
}

function animateDiv() {
  var $target = $('.a');
  var newq = makeNewPosition($target.parent());
  var oldq = $target.offset();
  /* Calculate duration in ms */
  var speed = calcSpeed([oldq.top, oldq.left], newq) + "ms";
  
  /* Set the duration of the animation */
  $(".a.animate").css("transitionDuration", speed);

  /* Set the new coordinates */
  $(".a").css({"top":newq[0], "left":newq[1]});
  
  /*
  $('.a').animate({
    top: newq[0],
    left: newq[1]
  }, speed, function() {
    animateDiv();
  });
  */
};

function calcSpeed(prev, next) {
  var x = Math.abs(prev[1] - next[1]);
  var y = Math.abs(prev[0] - next[0]);
  var greatest = x > y ? x : y;
  var speedModifier = 0.1;
  var speed = Math.ceil(greatest / speedModifier);
  return speed;
}
div#container {
  height: 100px;
  width: 100px;
  margin-left: 500px;
  background-color: yellow;
  position: relative; /* Added */
}

div.a {
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  top: 0; /* Initial position */
  left: 0; /* Initial position */
}

div.a.animate {
  transition: left, top;
  transition-duration: 1000ms; /* Default value */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1>TITLE!</h1>
  <p>
    Just some test which the red squere won't touch at any point
  </p>
</div>
<div id="container">
  <div class='a'></div>
</div>

Related