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);
});
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…
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] + ')');
});