Home > Back-end >  Reset button style after 2nd click
Reset button style after 2nd click

Time:03-02

I have a button that is used to display/hide information. I have a style for when the information is displayed, and another for when it's hidden. So far, I manage to change the initial style when the button is clicked thanks to "button:focus", but then the style remains unchanged when it's clicked again. I would basically need the style to be switched between those two styles at every click. Can someone help me ?

This is my CSS style.


#button1 {
    height:50px;
    width:170px;
    border-style: solid;
    font-weight: 700;
    text-transform: uppercase;
    font-size: 0.875rem;
    letter-spacing: 1px;
    font-family: "Roboto", serif;
    background-image: none;
    box-shadow: 2px 2px 8px 0 rgba(128,128,128,1);
    margin: 0 auto 0;
    border-color: white;
    color:white;
    background-color:rgb(4, 30, 78);
    border-radius: 30px;
  }

  #button1:hover {
    background-color: white;
    color:rgb(4, 30, 78);
    border-color:rgb(4, 30, 78);
    cursor:pointer;
  }

  #button1:focus{
    background-color: white;
    color:rgb(4, 30, 78);
    border-color:rgb(4, 30, 78);
    cursor:pointer;
  }

CodePudding user response:

You can use javascript on the onclick event to modify the button classList, please check the sample below

#button1 {
    height:50px;
    width:170px;
    border-style: solid;
    font-weight: 700;
    text-transform: uppercase;
    font-size: 0.875rem;
    letter-spacing: 1px;
    font-family: "Roboto", serif;
    background-image: none;
    box-shadow: 2px 2px 8px 0 rgba(128,128,128,1);
    margin: 0 auto 0;
    border-color: white;
    color:white;
    background-color:rgb(4, 30, 78);
    border-radius: 30px;
  }
  
  #button1.active {
    background-color: white;
    color:rgb(4, 30, 78);
    border-color:rgb(4, 30, 78);
    cursor:pointer;
  }
<button id="button1" onclick="this.classList.toggle('active')">Click Me</button>

Form more information please check Element.classList

CodePudding user response:

First, let's clean your code a little:

#button1 {
  display: block; /* You need this, if the element is <a>*/
  
  /*
   * height: 50px;            
  • Related