Simtwo Simtwo - 5 months ago 8
CSS Question

Change the starting point of an animation

I made an JavaScript animation of a div based on this fiddle: http://jsfiddle.net/Xw29r/15/
I am searching for a way to make the animation start from a precise point :

Top : 10vh
and
Left : 90vw
but I can't seem to find how to do it without placing the animation outside the window


thought about using math like
($(window).width()/100*9))

in order to have a vw size. But doesn't seem to work yet.
How could I achieve that ?

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

});

function makeNewPosition(){

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

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

return [nh,nw];

}

function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').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;

}

Answer

Use CSS calc() like this: left: calc(90vw - 50px); to make it stay within the window, as long as the windows is bigger than the div itself.

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

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

function animateDiv(){
    var newq = makeNewPosition();
    var oldq = $('.a').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.a {
  top: 10vh;
  left: calc(90vw - 50px);
  width: 50px;
  height:50px;
  background-color:red;
  position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='a'></div>