skip to Main Content

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!

2

Answers


  1. 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"')
    });
    
    Login or Signup to reply.
  2. You can try this:

    let num = 1 // Counter
    const picNum = 5 // Number of images in a folder
    $('#bg-change').on('click', function() {
      if (num == picNum){
        num = 1
      }else {
         num += 1
      }
      $('#background').css('background-image', 'url("./img/blank-wall'+num+'.jpg"')
    });
    

    At first you should specify the number of images then define a variable (num) that each time when you click the button add 1 to it or if that was equal to the number of images simply redefine it as 1 then it can change the background by the value of num variable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search