Pedro D.
Pedro D.

Reputation: 99

Move image randomly

I have this code that supposedly makes the image move around the page but It doesnt moves can someone identify the error.

Thanks.

My HTML :

<div id="container"> <span id="random"><img src="poke.png"></span> </div>

My JS :

<script>
function moveDiv() {
    var $span = $("#random");

    $span.fadeOut(270, function() {
        var maxLeft = $(window).width() - $span.width();
        var maxTop = $(window).height() - $span.height();
        var leftPos = Math.floor(Math.random() * (maxLeft + 1))
        var topPos = Math.floor(Math.random() * (maxTop + 1))

        $span.css({ left: leftPos, top: topPos }).fadeIn(270);
    });
};

moveDiv();
setInterval(moveDiv, 270);
</script>

My CSS :

<style>span { display: inline-block; position: absolute;}</style>

Upvotes: 0

Views: 1959

Answers (3)

solimanware
solimanware

Reputation: 3051

It works just include the jQuery into your code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
You can wrap your script code in document ready too.

$(document).ready()

Upvotes: 1

Iqbal Pasha
Iqbal Pasha

Reputation: 1316

try with below code, it might help you.

function moveDiv() {
    var $span = $("#random");

    $span.fadeOut(270, function() {
        var maxLeft = $(window).width() - $span.width();
        var maxTop = $(window).height() - $span.height();
        var leftPos = Math.floor(Math.random() * (maxLeft + 1))
        var topPos = Math.floor(Math.random() * (maxTop + 1))

        $span.css({ left: leftPos, top: topPos }).fadeIn(270);
    });
};

moveDiv();
setInterval(moveDiv, 270);
span { display: inline-block; position: absolute;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"> <span id="random"><img src="http://hiroki.jp/wp-content/uploads/2011/06/google-chrome-logo-100x100.png"></span> </div>

Upvotes: 6

Antonio Smoljan
Antonio Smoljan

Reputation: 2207

As you can see here your code works fine. The reason why in your case the code is not working is beacuse the script is not running when all of the DOM is loaded.

You can wrap your script code in document ready

$(document).ready()

Like the above comments mentioned, this ensures the code is ran when the DOM is loaded.

Upvotes: 1

Related Questions