mercredi 24 juin 2020

How to change the background image of an element randomly?

I have recently created a program which creates new element when someone clicks it. The new element which is created has some specific CSS styling. Now i want it's background to randomly change when the user clicks on button. Like the first time when someone clicks the background is red another time its green and so on like this.. My code is -

function a1click(){
      var body = document.querySelector('body');
        var bubbles = document.createElement("span");
        var size = Math.random() * 100;
        bubbles.style.width = 10 + size+'px';
        bubbles.style.height = 10 + size+'px';
        body.appendChild(bubbles);
        setTimeout(function(){
            bubbles.remove();
        },1000)      
  }
*{
    margin: 0;
    padding: 0;
}
body{
    background: rgb(73, 156, 145);
}
#a1{
    position: relative;
    top: 350px;
    left: 100px;
    width: 30px;
    height: 150px;
    border: 2px solid #fff;
    background: rgb(0, 0, 0);
    float: left;
    cursor: pointer;
    perspective: 600;
}
span{
    position: absolute;
    top: 120px;
    left: 60%;
    width: 50px;
    height: 50px;
    background: #000;
    animation: tweek 1s linear infinite;
    transform-origin: top;
    background-size: cover;
    pointer-events: none;
}
@keyframes tweek {
    0% {
      transform: rotate(90deg) translate(300px);
    }
  
    100% {
      transform: rotate(0deg) translate(250px);
      opacity: 0;
    }
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body onkeydown="keypress(event)">
    <div id="a1" onclick="a1click()"></div>
    <script src="script.js"></script>
</body>
</html>

I want the background color of this box to change randomly..Please help, any help is appreciated..




Aucun commentaire:

Enregistrer un commentaire