How To Animate A Box Flying Across The Screen using CSS

Now that we have random positioning and coloring settled, we need to start looking at a way to animate the box moving across the screen. Once upon a time, I would’ve just used Flash to make all this work, but vast improvements in HTML, CSS, and JavaScript have really (thankfully) eliminated the need to use Flash for this kind of work. There are now two main ways to animate objects on a web page: one using CSS and one using JavaScript (or jQuery). We’ll start by looking at the CSS method.

I made a few minor changes to the previous HTML & JavaScript files so that it draws 2 div containers, each a random color, and places them at some random Y position along the left side of the screen. For visual clarity, I made one square 300px and one 200px:

iteration2.js

function makebox() {
    var top1=Math.random();
    var top2=Math.random();
    top1=top1*100;
    top2=top2*100;
    document.getElementById("box1").style.top=top1+"px";
    document.getElementById("box1").style.backgroundColor=getRandomColor();
    document.getElementById("box1").style.display="block";
    \document.getElementById("box2").style.top=top2+"px";
    document.getElementById("box2").style.backgroundColor=getRandomColor();
    document.getElementById("box2").style.display="block";
}

iteration2.html

<html>
<head>
<script type="text/javascript" src="iteration2.js"></script>
<style type="text/css">

    div {
        animation-name: example;
        animation-duration: 4s;
        animation-iteration-count: infinite;
    }

    @keyframes example {
        0%   {left:0%;}
        100% {left:100%;}
    }

    #box1 {
        width:200px;
        height:200px;
        background-color:red;
        display:none;
        position:relative;
    }

    #box2 {
        width:300px;
        height:300px;
        background-color:red;
        display:none;
        position:relative;
    }
</style>
</head>

<body onload="makebox();">

<div id="box1"></div>
<div id="box2"></div>

</body>
</html>

In the CSS section of the HTML document, we see that div containers in this document will be animated and that animation will have a duration of 4 seconds, repeating infinitely. The @keyframes parameters define two keyframes for this 4 second animation: 0% (the beginning) and 100% (the ending). We could add other keyframes in between, but for simplicity, we’ll just stick with the requisite two.

0% {left:0%;} defines the first keyframe of the animation, placing the object to be animated at the left edge of the screen.

100% {left:100%;} declares that the last keyframe of the animation will see the object at the right edge of the screen.

Note that the animation is the same for every iteration of the loop. In order to see different combinations of colors and starting positions, you’ll need to refresh the page.

How To Detect Browser User Agent And Add Mobile Website Support

There remains one major problem with the application as it stands right now: when viewed on a mobile browser, the animation breaks down and the viewer window causes undesirable effects such as rescaling the page. As such, we’ll need to tweak the operation just slightly for mobile browsers (this wasn’t such a problem in the 1990s and early 2000s, but with most web browsing done via mobile, it would be dumb not to account for the difference.

iteration7.html

<script>
$(document).ready(function(){
       detectUserAgent();
    });
</script>

In the main HTML file, the only change we’re going to make is calling a different function from our JS file. In this case, it’s a function that will detect the user agent, letting the application know whether to run the desktop or mobile version of the app.

iteration7.js

function detectUserAgent() {
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i))) {
        location.replace("mobile.html");
    }
    startplayer();
    }

function startplayer() {
    $.getScript("videofiles.js", function() {
        });
    makebox();
    }

In the JavaScript, the new detectUserAgent() function queries the navigator.userAgent object to see if it contains the string “iPhone”, “iPad”, or “Android” which would indicate a mobile device and browser. If one of those strings is found in the object, then the current page is redirected to “mobile.html”. Otherwise, the startplayer() function is called.

In the startplayer() function, we use the jQuery getScript() method to load another JS file within the script as running. In this case, it will load the “videofiles.js” file that now contains the addresses array.

The “mobile.html” file works exactly like the main HTML file, except that it now refers to a slightly different JS file, “mobile.js” that contains the changes we need to make the mobile version work.

mobile.js

function makebox() {
    $(".window").click(function () {
        video = $(this).css("background-image");
        video = video.slice(32, -6);
        window.open("https://www.youtube.com/embed/"+video, '_blank');
    });
    $(".window:not(:animated)").each(function() {
        addy = (Math.floor(Math.random() * addresses.length));
        $(this).css({"top": Math.random() * window.innerHeight - 290+"px","left": "-"+Math.random() * 740 - 740+"px","background-image": "url('https://img.youtube.com/vi/"+addresses[addy]+"/0.jpg')", "border": "10px solid", "color": getRandomColor});
        $(this).animate({left: "2000px"}, Math.random() * 15000 + 15000, makebox);
    });
    }

We only need to make two major changes to the makebox() function to make it work on mobile: First, we need to make sure that we define all animations by pixel distances instead of screen widths. The percentage screen width method of measurement does not work correctly on some mobile browsers and can cause the flying windows to rescale themselves when they reach the right edge of the screen.

window.open("https://www.youtube.com/embed/"+video, '_blank');
Second, instead of a viewer div playing an embedded YouTube video, we’re going to open the video in a new tab. We’re still going to use the embed version of the video, though, to avoid having the full YouTube player page load (which would also be undesirable).

From this point, we just add an appropriate background video to the HTML file body using the background-video CSS property, some appropriate MIDI music using the MIDIjs JavaScript library (midijs.net), and a few navigation buttons, and the application is ready to go!