Skip to content

Instantly share code, notes, and snippets.

@mikestratton
Created February 28, 2019 07:33
Show Gist options
  • Save mikestratton/62f5bcbe9d8b701fe1d36d66652cbd2d to your computer and use it in GitHub Desktop.
Save mikestratton/62f5bcbe9d8b701fe1d36d66652cbd2d to your computer and use it in GitHub Desktop.
Random Moving Div
<div class='a'></div>
<div class='b'></div>
<div class='c'></div>
<div class='d'></div>
$(document).ready(function(){
animateDiv('.a');
animateDiv('.b');
animateDiv('.c');
animateDiv('.d');
});
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(myclass){
var newq = makeNewPosition();
$(myclass).animate({ top: newq[0], left: newq[1] }, 1000, function(){
animateDiv(myclass);
});
};
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
div.b {
width: 50px;
height:50px;
background-color:blue;
position:fixed;
}
div.c {
width: 50px;
height:50px;
background-color:green;
position:fixed;
}
div.d {
width: 50px;
height:50px;
background-color:yellow;
position:fixed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment