onClick change background picture of div

I’ve tried placing the array inside and out of the page ready, same with the onclick… thinking maybe it could just be an issue with scope. But when I console.log(backgroundImg); on the last line, I’m still getting the [1] out of the array… it doesn’t seem to be picking up the assignment to [0]…

  var backgroundImg = [
    'http://cdn.wallpapersafari.com/93/91/K41BiL.jpg',
    'http://www.pixelstalk.net/wp-content/uploads/2015/12/kansai-new.jpg'
  ]; //Add more backgrounds to the array

$(function() {



  $('body').css('background-image', 'url(' + backgroundImg[1] + ')'); //allows a variable for changing background img based in an array, change number in [] to change background...



});


$('#onClick').on('click', function(){
  $('#body').css('background-image', 'url(' + backgroundImg[0] + ')');
  console.log(backgroundImg);
});

http://codepen.io/TurtleWolf/pen/aJNgpg?editors=1011

ok, I solved that… it was not an ‘id =’ just ‘body’, but now I want to switch it to a toggle to go back and forth or maybe even something to cycle through the whole are and till you click on the button the length of the array back to zero… I think I can work that one out…

1 Like

Yup, the selector problem was the looking for the id.

For the swap, all you need to do is set yourself a variable, then handle it that way…

var backgroundImg = ['http://cdn.wallpapersafari.com/93/91/K41BiL.jpg',
                     'http://www.pixelstalk.net/wp-content/uploads/2015/12/kansai-new.jpg'
                    ]; //Add more backgrounds to the array
var backgroundCount = 0;

$(function() {
  $('body').css('background-image', 'url(' + backgroundImg[backgroundCount] + ')'); //allows a variable for changing background img based in an array, change number in [] to change background...
});

$('#onClick').on('click', function(){
  backgroundCount++;
  if (backgroundCount > backgroundImg.length - 1) backgroundCount = 0;
  $('body').css('background-image', 'url(' + backgroundImg[backgroundCount] + ')');
});
2 Likes

yes, that works perfectly! Thank you, i was preparing a 2nd question to get just this answer!

1 Like

You could do it like this, keep things a bit more modular:

(function(){
  var clickCount = 0;
  var backgroundImg = [
    'http://cdn.wallpapersafari.com/93/91/K41BiL.jpg',
    'http://www.pixelstalk.net/wp-content/uploads/2015/12/kansai-new.jpg'
  ];

  $('button').on('click', function(){
    var i = clickCount % backgroundImg.length;
    $('body').css('background-image', 'url(' + backgroundImg[i] + ')');
    clickCount++;
  })
  .click();
})();

BTW, I changed the #onClick element to be a button.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.