bigpotato
bigpotato

Reputation: 27497

jQuery/JS random image positioning using Math.random() and .css?

I'm new to programming. Right now I'm using jQuery + jqueryrotate to rotate my images randomly so it looks like they are scattered. I managed to make them rotate randomly, but I am a little stuck on how to make the position random. I made all the images position: absolute in a position: relative div with class .holder. I know usually the css property using jquery should normally be ({"top": "4px"}) but I want it doesn't work when I wrap it around a toString function.

$.each($('.holder img'), function (i, element) {
    $(element).rotate(Math.random() * -90 + Math.random() * 90);
    $(element).css({
        "top": Math.random() * 300;
    })
});

Upvotes: 0

Views: 2391

Answers (3)

Firnas
Firnas

Reputation: 11

You just add + "px" at the end of the CSS value of the top attribute

$(element).css({
    "top": (Math.random () * 300) + "px"
});

Upvotes: 0

Lucas Green
Lucas Green

Reputation: 3959

Without a unit top doesn't know what you mean, try this:

$.each($('.holder img'), function(i, element){
    $(element).rotate(Math.random() * -90 + Math.random() * 90);
    $(element).css({
        "top": (Math.random() * 300) + "px"
    })
});

Upvotes: 4

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

$(element).css({
    "top": Math.random() * 300;
});

should be

$(element).css({
    "top": Math.random() * 300
});

remove ; or it'll trigger a sintax error.

Upvotes: 2

Related Questions