How to move element randomly across screen (css or jquery)?

1

How to make an element move around the screen by randomly bouncing around the edges of the screen. Like those screensavers of old DVDs?!??

The closest example that I found my question was in css (keyframes, transforms, animations, etc ...) bad makes the code very extensive because I needed to add "some" more elements. Example .

If anyone has equivalent (and minor) solution in jquery thank you right away.

    
asked by anonymous 03.09.2014 / 06:27

1 answer

1

I made an example in the jsfiddle adapted as a basis This answer .

JAVASCRIPT

$(document).ready(function()
{
    $('.bouncer').click( function(){
        alert('clicaram no: ' + $(this).attr('title'));
    });
});

$(function() {
    var minSpeed = .02;
    var maxSpeed = .06;
    var varSpeed = .005;

    function startBounce(element) {
        var container = element.parent();
        var width = container.innerWidth() - element.outerWidth();
        var height = container.innerHeight() - element.outerHeight();

        var vertSpeed = ((Math.random() * (maxSpeed - minSpeed)) + minSpeed);
        var horzSpeed = ((Math.random() * (maxSpeed - minSpeed)) + minSpeed);
        bounce(element, vertSpeed, height, 'top');
        bounce(element, horzSpeed, width, 'left');
    }

    function bounce(element, speed, max, dir) {
        speed += ((Math.random() * varSpeed) - (varSpeed / 2));
        speed = speed < minSpeed ? minSpeed : (speed > maxSpeed ? maxSpeed : speed)
        var time = max / speed;
        var position = element.position();
        if (position[dir] < 2) {
            target = max;
        } else {
            target = 0;
        }

        var style = {
            queue: false
        };
        style[dir] = target;
        element.animate(style, {
            duration: time,
            queue: false,
            easing: "linear",
            complete: function() {
                bounce(element, time, max, dir);
            }
        });
    }

    startBounce($('#bouncer1'));
    startBounce($('#bouncer2'));
});

CSS

#container{position:absolute; width:300px; height:200px}
.bouncer{position:absolute; width:20px; height:20px;}

HTML

<div id="container">
    <div class="bouncer" id="bouncer1" title="bouncer 1">•</div>
    <div class="bouncer" id="bouncer2" title="bouncer 2">•</div>
</div>

I'm keeping the source code here as a guarantee, because the original question in SOEN was given as a duplicate of an issue that has already been removed.     

03.09.2014 / 08:42