Kathan
Kathan

Reputation: 1458

Javascript Changing Random Background Image Issue

I am on Rails 4, and finally got this javascript working. It changes randomly changes the background image every 10 seconds with a fadein fadeout effect.

The only issue is every so often, an image will only load halfway... then it will start to flash and and get crazy. It will continue to erratically flash from picture to picture until i refresh the page.

Does anyone know why this is happening? Maybe poorly written javascript? All of my pictures are located in public/assets.

home.html.erb:

<div id="imageDiv" class="imageContainer"></div>

  <script>
    var myImages = new Array("sushi.jpg", "pizza.jpg", "steak.jpg", "greens.jpg", "pancakes.jpg", "redbull.jpg", "coffeepow.jpg", "frenchfries.jpg", "tabs.jpg", "cigarettes.jpg", "noodles.jpg", "jelly.jpg", "pills2.jpg", "pills3.jpg", "gator.jpg", "needle.jpg", "tv.jpg", "cantop.jpg", "spices.jpg", "sliders.jpg", "fishoil.jpg", "chips.jpg", "cherries.jpg", "ciglighter.jpg", "eggs.jpg", "bakingsoda.jpg", "pasta.jpg", "beer.jpg", "champagne.jpg", "peppers.jpg");

    $(document).ready(function() {
        var random = myImages[Math.floor(Math.random() * myImages.length)];
        random = 'url(assets/' + random + ')';
        $('#imageDiv').css('background-image', random);

        setInterval(function() {
            SetImage();
        }, 10000);
    });

    function SetImage() {
        var random = myImages[Math.floor(Math.random() * myImages.length)];

        random = 'url(assets/' + random + ')';
        $('#imageDiv').fadeOut(900);

        setTimeout(function () {
            $('#imageDiv').css('background-image', random);
            $('#imageDiv').fadeIn(900);
        }, 900);
    }
  </script>

Upvotes: 0

Views: 275

Answers (1)

Oleg Berman
Oleg Berman

Reputation: 714

I don't really want to get deep into your code, in two words: whatever is happening is happening because you have to wait for some actions to complete before they complete (such as animations) and you never want have timeouts within intervals.

This has to be helpful:

var images = ["http://i.imgur.com/xYDljlP.jpg",
          "http://i.imgur.com/f9MgLTO.jpg",
          "http://i.imgur.com/ECM9LKl.jpg"];


function setBackground() {
    var rand = Math.floor(Math.random() * images.length);
    $( "#imageDiv" ).fadeOut(300, function() {
      $( "#imageDiv" ).css("background", "url( " + images[rand] + " )");
      $( "#imageDiv" ).fadeIn(300, function() {
         setTimeout(setBackground, 3000);
      });
    });
}

setBackground();

Please see the fiddle: jsfiddle

Upvotes: 1

Related Questions