0

I want to randomly animate the body's background-position in an interval. There are a few predefined background-position values (x, y) stored in an array.

Here's the script so far:

$(document).ready(function() {
    var xyz = new Array();
    xyz[1] = "backgroundPosition: '0% 0%'";
    xyz[2] = "backgroundPosition: '53% 34%'";
    var item = xyz[Math.floor(Math.random()*xyz.length)];

    var move = setInterval(function(){
        $('body').animate({item}, 2000);
    }, 7000);
});

Can someone tell me where the issue is? Any code optimizations? Thanks alot!

James Cazzetta
  • 3,122
  • 6
  • 32
  • 54

2 Answers2

1

You are not setting item each time. Modified code. In your code item is being set only once. Moving that line inside setInterval will change item set every time.

 $(document).ready(function() {
        var xyz = new Array();
        xyz[1] = {"backgroundPosition": '0% 0%'};
        xyz[2] = {"backgroundPosition": '53% 34%'};     

        var move = setInterval(function(){
            var item = xyz[Math.floor(Math.random()*xyz.length)];
            $('body').animate(item, 2000);
        }, 7000);
    });
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • Thanks, though this throws following error (in FF 15.0.1): "SyntaxError: invalid object initializer $('body').animate({item}, 2000);" – James Cazzetta Sep 28 '12 at 14:32
  • 1
    @James Cazzetta You are not passing correct value I made the change. have a look. – Anoop Sep 28 '12 at 14:35
1

Item should be redefined every time. And also, Math.floor(Math.random()*xyz.length) can be 0 so I added 1+ to your calculation since you start at key 1 on xyz.

 $(document).ready(function() {
        var xyz = new Array();
        xyz[1] = {backgroundPosition: '0% 0%'};
        xyz[2] = {backgroundPosition: '53% 34%'};     

        var move = setInterval(function(){
            var item = xyz[1+Math.floor(Math.random()*(xyz.length-1))];
            $('body').animate(item, 2000);
        }, 7000);
    });
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • Thanks, though this throws following error (in FF 15.0.1): "SyntaxError: invalid object initializer $('body').animate({item}, 2000);" – James Cazzetta Sep 28 '12 at 14:31