Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery, changing background image with timer

I have two background images I am using for this website and I want them to change automatically every 5 seconds. Can someone please look at my jQuery code and tell me what I am doing wrong?

$(function() {
    var body = $(‘body’);
    var backgrounds = new Array(
        ‘url(images/hso-palmtree-background.jpg)’,
        ‘url(images/hso-boardwalk-background.jpg)’
    );

    var current = 0;

    function nextBackground() {
        body.css(
           ‘background’,
            backgrounds[current = ++current % backgrounds.length]
        );

        setTimeout(nextBackground, 5000);
    }

    setTimeout(nextBackground, 5000);
    body.css(‘background’, backgrounds[0]);
});
like image 741
Joseph Montecalvo Avatar asked Feb 27 '14 17:02

Joseph Montecalvo


1 Answers

You code is correct, you just need to change the backticks. Change to '.

Here is a cleaned revision: http://jsfiddle.net/X2NqX/

$(function () {
    var body = $('body');
    var backgrounds = [
      'url(http://static.jsbin.com/images/jsbin_static.png)', 
      'url(http://static.jsbin.com/images/popout.png)'];
    var current = 0;

    function nextBackground() {
        body.css(
            'background',
        backgrounds[current = ++current % backgrounds.length]);

        setTimeout(nextBackground, 5000);
    }
    setTimeout(nextBackground, 5000);
    body.css('background', backgrounds[0]);
});
like image 64
Majid Fouladpour Avatar answered Sep 24 '22 08:09

Majid Fouladpour