Created
June 5, 2013 15:07
-
-
Save Agnostic/5714576 to your computer and use it in GitHub Desktop.
Simple bouncing ball with jQuery.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create element | |
var _ball = document.createElement('div'); | |
_ball.className = 'ball'; | |
// CSS | |
$(_ball).css({ | |
width: '40px', | |
height: '40px', | |
borderRadius: '50%', | |
position: 'fixed', | |
top: 0, | |
left: 0, | |
background: 'lightblue', | |
}); | |
// Append to body | |
$('body').append(_ball); | |
// Initial direction | |
var dirX = true, | |
dirY = true; | |
// Move function | |
var move_ball = function(){ | |
var vel = 5; // Timeout milliseconds | |
setTimeout(function(){ | |
var ball = $('.ball'); | |
var posLeft = ball.position().left, | |
posTop = ball.position().top; | |
var moveX; | |
// If dirX is true | |
if(dirX){ | |
moveX = posLeft+1; | |
} else { | |
moveX = posLeft-1; | |
} | |
// Move ball (X) | |
ball.css({ left: moveX + 'px' }); | |
if( dirX ){ | |
if( posLeft < $(window).width()-ball.width() ){ | |
dirX = true; | |
} else { | |
dirX = false; | |
} | |
} else { | |
if( posLeft <= 0){ | |
dirX = true; | |
} else { | |
dirX = false; | |
} | |
} | |
var moveY; | |
// If dirY | |
if(dirY){ | |
moveY = posTop+3; | |
} else { | |
moveY = posTop-3; | |
} | |
// Move ball (Y) | |
ball.css({ top: moveY + 'px' }); | |
if( dirY ){ | |
if( posTop <= $(window).height()-ball.height() ){ | |
dirY = true; | |
} else { | |
dirY = false; | |
} | |
} else { | |
if( posTop <= 0){ | |
dirY = true; | |
} else { | |
dirY = false; | |
} | |
} | |
// Move ball, again! | |
move_ball(); | |
}, vel); | |
}; | |
move_ball(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment