Home > front end >  change image in a circle
change image in a circle

Time:02-17

I have a button and a function that on click changes the background image

But it only works once. How can I make so that the click button always works and the change of images does not stop, but changes in turn?

function myFunction() {
   document.getElementById("image").style.backgroundImage = "url(https://i.picsum.photos/id/187/200/200.jpg?hmac=b_8v5WKwO-_jC2FqfZOP_n9niD1jQvZHB31GoegK2Ww)";
}
#image {
  width: 200px;
  height: 200px;
  background-image: url("https://i.picsum.photos/id/1008/200/200.jpg?hmac=I0T_cpYR-61pUlB0jVB4I5B7tL0fvzN5MgslAOirM50");
}
  
button {
  margin-bottom: 10px;
}
<button onclick="myFunction()">Change</button>

<div id="image"></div>

CodePudding user response:

function myFunction() {
               document.getElementById("image").classList.toggle("newBg");
            }
 #image {
      width: 200px;
      height: 200px;
      background-image: url("https://i.picsum.photos/id/1008/200/200.jpg?hmac=I0T_cpYR-61pUlB0jVB4I5B7tL0fvzN5MgslAOirM50");
    }
   
   
   #image.newBg{
    background-image: URL("https://i.picsum.photos/id/187/200/200.jpg?hmac=b_8v5WKwO-_jC2FqfZOP_n9niD1jQvZHB31GoegK2Ww");
    }
      
    button {
      margin-bottom: 10px;
    }
<button onclick="myFunction()">Change</button>
    
    <div id="image"></div>

If you want to change the image with every click, you need to toggle it. You can simply use a class-based approach out of many other solutions.

Eg:

function myFunction() {
           document.getElementById("image").classList.toggle("newBg");
        }

#image {
  width: 200px;
  height: 200px;
  background-image: url("https://i.picsum.photos/id/1008/200/200.jpg?hmac=I0T_cpYR-61pUlB0jVB4I5B7tL0fvzN5MgslAOirM50");
}

#image.newBg{
background-image: URL("https://i.picsum.photos/id/187/200/200.jpg?hmac=b_8v5WKwO-_jC2FqfZOP_n9niD1jQvZHB31GoegK2Ww");
}
  
button {
  margin-bottom: 10px;
}

<button onclick="myFunction()">Change</button>

<div id="image"></div>

CodePudding user response:

there is a CSS element called border radius apply this to the image and it will gonna change into circle

border-radius: 50%;
  • Related