skip to Main Content

I have created a button that changes the background color to gradient and when I double click it, it returns back. When I click the button, it changes the color and text(hello) of itself to gradient and text(hi), but when I double click it, the button doesn’t return back, it just shows the gradient and text(hi). I tried the codes answered to the question ‘toggle button background color when clicked’ they are also not working. Can you help me to solve this problem?

I tried some javascript code, that I found in stack overflow. But it is not working.

function myFunction() {
  document.body.style.background = "linear-gradient(orange, white, green)";
}

function myFunction2() {
  document.body.style.background = "#22232e";
}
<button onclick="myFunction()" ondblclick="myFunction2()">
<span>hello</span>
<span>hi</span>
</button>

2

Answers


  1. You can achive this using css transition property.If you want it change it’s background color countinuously then you can try keyframes animation.And for click event you can use ‘:focus’ pseudo-class.For example——
    css property

    #button{
       background-color: red;
    
       transition: background-color 2s linear;
    }
    
    #button:focus{
    
    background-color: purple;
    
    }
    

    Or you can use keyframes animation.It will change background color infinite loop after click on the button. For example—

    #I{
                background-color: black;
                transition: background-color 2s linear ;
                color: wheat;
    }
    
    @keyframes colors {
                from{
                    background-color: red;
                }
                to{
                    background-color: purple;
                }
    }
    #I:focus{
                animation: colors 2s linear infinite alternate;
    }
    
    Login or Signup to reply.
  2. <button onclick="myFunction()" ondblclick="myFunction2()">
        <span class="hello"> hello </span>
        <span  class="hii" style="display:none;"> hii </span>
    </button>
    

    //here`s the js

    function myFunction () {
         document.body.style.backgroundColor ="grey";
         document.querySelector('.hello').style.display ="none";
         document.querySelector('.hii').style.display ="inline-block";
      }
      
      function myFunction2 () {
         document.body.style.background ="initial";
         document.querySelector('.hello').style.display ="inline-block";
         document.querySelector('.hii').style.display ="none";
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search