Search code examples
javascriptjqueryonclickbackground-image

How can I change the background image to a different image each time I click a button?


I'm using jQuery to try to change the background-image each time I click a button. Currently my background is going through a for loop each time the button is clicked, so the picture is going straight from the first picture to the last picture in my folder.

I know this is not what I'm aiming for but this is the only thing I've been able to get work without throwing errors:

$('#bg-change').on('click', function() {
  for (let i = 1; i < 5; i++) {
    $('#background').css('background-image', 'url("./img/blank-wall'+i+'.jpg"')
  };
});

I've tried using an array as well as toggling classes but it can only get it to change between two images.

Please help!


Solution

  • You don't need the for loop you can just use a counter variable and an if statement and it should work.

    let imgIndex = 0;
    
    $('#bg-change').on('click', function() {
      imgIndex ++;
    
      if (imgIndex > 4) {
        imgIndex = 1;
      }
    
      $('#background').css('background-image', 'url("./img/blank-wall'+imgIndex+'.jpg"')
    });