0

i have following script like :

/* jshint loopfunc:true */
var url = [
    "http://protiumdesign.com/wp-content/uploads/2015/04/Material-Design-Background-1024.jpg",
    "http://i.imgur.com/wt4NRqA.jpg",
    "http://i0.wp.com/thezinx.com/wp-content/uploads/md-6.png"
];

$(document).ready(function() {
    changeBack();

    function changeBack() {
        for (var i = 0; i < url.length; i++) {

            $('#elem').fadeTo('slow', 0.3, function() {
                $(this).css('background-image', 'url(' + url[i] + ')');
            }).fadeTo('slow', 1).delay(1000);
        }
        changeBack();
    }
});

the function above for change the background image dynamically but the array is undefined within the function, how to fix that , thank you

this is the fiddle : Here

3
  • everything is right, just your loop is wrong for (var i = 0; i < url.length-1; i++) { $('#elem').fadeTo('slow', 0.3, function() { $(this).css('background-image', 'url(' + url[i] + ')'); }).fadeTo('slow', 1).delay(1000); } It should be length-1 rather than length Commented Jul 28, 2015 at 5:01
  • jsfiddle.net/9Lqc47dq/7 Commented Jul 28, 2015 at 5:02
  • @BrijRajSingh: no, you should make the i parameter bound to the callback function, making the length - 1 will perform 2 "changes" to index 2, like function(localI) { $(this).css('background-image', 'url(' + url[localI] + ')'); }.bind(this, i), see jsfiddle.net/Icepickle/9Lqc47dq/9 Commented Jul 28, 2015 at 5:26

1 Answer 1

4

Although one of the issues described here is a duplicate of JavaScript closure inside loops – simple practical example, there are other issues like infinite recursive call of changeBack.

I think a better approach will be

/* jshint loopfunc:true */
var url = ["http://protiumdesign.com/wp-content/uploads/2015/04/Material-Design-Background-1024.jpg", "http://i.imgur.com/wt4NRqA.jpg", "http://i0.wp.com/thezinx.com/wp-content/uploads/md-6.png"];

$(document).ready(function() {
  var i = 0;

  function changeBack() {
    $('#elem').fadeTo('slow', 0.3, function() {
      $(this).css('background-image', 'url(' + url[i++] + ')');
      i = i < url.length ? i : 0
    }).fadeTo('slow', 1).delay(1000).promise().done(changeBack);
  }
  changeBack();
});
#elem {
  width: 500px;
  height: 300px;
  background-size: 100%;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='elem'></div>

Sign up to request clarification or add additional context in comments.

Comments

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.