Search code examples
javascriptarraysfunctionclickbackground-image

Change background image array by javascript click


I am a total beginner in javascript and have the following problem.

I want to change the background image of a div when the user clicks on it. But instead of just one picture, through a series of pictures. So that a new picture appears for every click. (1.jpg, 2.jpg, …, 5.jpg) It must be done by replacing the css background image url, otherwise other functions will no longer work. So far i can only exchange one picture per click.

This is the current code:

HTML:

<div class = "image"></div>

CSS:

.image{
   position: absolute;
   background-image: url ("1.jpg");
   background-size: cover;
}

JS:

$ (document) .ready (function () {
           $ (". image"). on ("click", function () {
               $ (". image"). css ({'background-image': 'url (2.jpg)'});
           });
   });

Thank you for your help!


Solution

  • You can do it like this, such as there are 5 images, make images 5:

    // possible image count
    const images = 5;
    
    $(document).ready(function () {
      let current = 0;
      $(".image").on("click", function () {
        $(".image").css({ 'background-image': `url(${++current % images + 1}.jpg)` });
      });
    });
    

    If you have a non-numerical image list, you can manually create an array for it like this:

    // put all possible image urls in this list
    const images = ['1.jpg', '2.jpg', '3.jpg', 'cat.jpg', 'dog.jpg'];
    
    $(document).ready(function () {
      let current = 0;
      $(".image").on("click", function () {
        $(".image").css({ 'background-image': `url(${images[++current % images.length]})` });
      });
    });