James Rand
James Rand

Reputation: 57

Jquery randomise position of a div from a predifined list

I have been trying to randomize the position of a div from a predefined list of positions in an array but have not been successful i think i might be close but i cant see where im going wrong.

var positionArray = [];

    function Position(left, top) {
        this.left=left;
        this.top=top;
    }

    function rand(ar){
        return 0.5-Math.random();
    }

    var positionArray = [
          new Position(0,  0) 
        , new Position(50, 50) 
        , new Position(100,100) 
        , new Position(150,150) 
        , new Position(200,200) 
        , new Position(250,250) 
        , new Position(300,300) 
        , new Position(350,350) 
    ];

    function init() {                
            var min = 0;
            var max = 7;
            var posIndex = Math.floor(Math.random() * (max - min + 1)) + min;
            alert(posIndex)                               
            $(".start-journey-marker").css({
                top     : positionArray[posIndex].top,
                left    : positionArray[posIndex].left
            });
    };

    positionArray.sort(rand);

    init(); 

see example here: http://jsfiddle.net/qQWYW/

Can you please help.

Upvotes: 0

Views: 103

Answers (3)

nnnnnn
nnnnnn

Reputation: 150010

For the CSS top and left to take effect you need to add position : relative or position : absolute to the element. (EDIT: or add position : fixed.)

Also your demo didn't work because you hadn't included jQuery (framework panel on the left).

Updated demo: http://jsfiddle.net/qQWYW/1/

Upvotes: 1

Selvakumar Ponnusamy
Selvakumar Ponnusamy

Reputation: 5533

Please add position property to your .start-journey-marker in your css

Upvotes: 0

Michael
Michael

Reputation: 1207

It is a styling matter. Just add

position: absolute;

to your .start-journey-marker selector.

P.S. It wont work on fiddle because you forgot to include jQuery.

Upvotes: 0

Related Questions