Home > database >  Are there any ways to return to original state after click on a button?
Are there any ways to return to original state after click on a button?

Time:03-31

i want after click on button the background back to the original color (blue) but after i have clicked button, it stays on the focus color (green color). is there any solution for my situation? i have tested some ways like animation but it failed. here are my codes:

<button>button</button>
           
<style>
    button {
        padding: 10px 35px;
        background-color: blue;
        color: #fff;
    }
    button:focus {
        background-color: green;
    }
</style>

CodePudding user response:

You should replace "button:focus" with "button:hover". This way the color of the button changes on hover (which you are doing when clicking a button). When the mouse leaves the element, the button has it's original color back. Look at the code below:

  <button>button</button>

       

  <style>
          button {
              padding: 10px 35px;
              background-color: blue;
              color: #fff;
          }
          button:hover {
                  background-color: green;
              }
      </style>

CodePudding user response:

const btn = document.querySelector("button")

btn.setAttribute("class", "")

btn.addEventListener("mouseenter", () => {
  btn.classList.add("green")
})

btn.addEventListener("mouseleave", () => {
  btn.classList.remove("green")
})

btn.addEventListener("click", () => {
  btn.classList.remove("green")
})
button {
  padding: 10px 35px;
  background-color: blue;
  color: #fff;
}
button.green {
  background-color: green;
}
<button>button</button>

  • Related