6

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]);
});
3
  • right now it is doing absolutely nothing. There is no background showing. But I know for sure it's getting the images because I set one of them as my background with CSS just to make sure and it did work. Commented Feb 27, 2014 at 17:15
  • Ok. The next time you make a question, put that information in it. Now, do you have any errors if you open firebug or something similar? Commented Feb 27, 2014 at 17:17
  • No, there are none that is why I am so confused. Is there anyone way of writing this out? Just FYI, I never declared any background image in my actual CSS since I am doing it with Jquery. Commented Feb 27, 2014 at 17:22

1 Answer 1

27

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]);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Works good, in my case I had to reset the CSS as it overrode the style sheet, example mainImg.css({ 'background':backgrounds[0], 'background-repeat':'repeat-x', 'background-position':'top', 'height':'654px', 'position':'absolute', 'top':'187px', 'width':'100%', 'z-index':'-1', });
How would one add a css-transition to this? Apologies as this question is pretty old.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.