Make a frisbee (or any other object) fly across your webpage

30th March, 2014 – 10:26 pm

I help run a community Ultimate Frisbee club in Manchester. I’ve just changed our design to make it responsive (mobile, tablet and desktop friendly) whilst aligning it to our “brand” colours and identity. Unfortunately it looked a little bit bland – we all thought it needed a bit of fun so I wanted a spinning frisbee to fly across the page!

Here’s how I did it.

1. Make an animated, transparent GIF – I wanted people to be able to “catch” the disc so I make the image canvas larger than it needed to be to make the click target bigger. Unfortunately GIFs are rubbish so it looks a bit jaggy.

DUFFA Ultimate Ultrastar frisbee animated spin

This one doesn’t fly across the page – see http://www.duffa.org for a live demo!

2. Add the following HTML (adjust for your image!).

<div id="flyingdisc"><a href="/caughtdisc"><img alt="" src="images/spinning_disc.gif" /></a></div>

3. Add the following CSS (again if you change the ID of the div change this.

 #flyingdisc {
 position:absolute;
 top:50px;
 left:-200px;
 display: none;
 }

4. Now add the following JQuery / JS.

$(document).ready(function() {
 // Using default configuration
// Using custom configuration
 $("#image_list").carouFredSel({
 items : 5,
 scroll : {
 items : 1,
 easing : "elastic",
 duration : 500,
 pauseOnHover : true
 }
 });
// if the flying disc div exists
 if ($('#flyingdisc').length){
 $('#flyingdisc').show();
 var wait;
 // get a random wait time - between 5 to 15 secs
 wait = randomIntFromInterval(5, 15) * 1000;
 // wait = 1000; // for testing
 setTimeout(function (){
 animateDiv();
 }, wait);
 }
 });
function makeNewPosition(){
// Get dimensions (remove the dimension of the div) - we use doc height but viewport width
 var h = $(document).height(); - 180;
 var w = $(window).width() - 180;
 var nh;
 var nw;
// new height from height of the doc
 nh = randomIntFromInterval(0, h);
 // if disc is on the right fly to the left, o/w to the right
 if ($('#flyingdisc').offset().left > 0) {
 nw = -100;
 } else {
 nw = $(window).width() - 180; // minus width to avoid scroll bars
 }
return [nh,nw];
}
function animateDiv(){
 // div must be visibile for calcs
 $('#flyingdisc').show();
 var newq = makeNewPosition();
 var oldq = $('#flyingdisc').offset();
var speed = 3000;
// get a random wait time - 5 to 15 secs
 var wait;
 wait = randomIntFromInterval(5, 15) * 1000;
$('#flyingdisc').animate({ top: newq[0], left: newq[1] }, speed, function(){
 $('#flyingdisc').hide();
 setTimeout(function (){
 // delay the animation
 animateDiv();
 }, wait);
 });
 };
function randomIntFromInterval(min,max)
 {
 return Math.floor(Math.random()*(max-min+1)+min);
 }

Viola! You can see a working demo on our DUFFA Homepage (it flies across the page at random intervals!).

Some points:

 

Post a Comment