简体   繁体   中英

How to toggle button colour when it is clicked and change the colour back to its previous colour when it is clicked again

I have to make a button that is used for starring messages. Initially the colour of the button is white, when I click on the button it should change the colour to golden and when clicking the same button again(unstarring messages), the colour should change the colour again to the initial background colour i:e white.

HTML: <button class="btn-hold" data-text-swap=" Starred!">Star Message!</button>

JavaScript(for toggling the messages on the button):

button.addEventListener('click', function() {
  if (button.getAttribute("data-text-swap") == button.innerHTML) {
    button.innerHTML = button.getAttribute("data-text-original");
  } else {
    button.setAttribute("data-text-original", button.innerHTML);
    button.innerHTML = button.getAttribute("data-text-swap");
  }
}, false);

CSS:

.btn-hold{

    float: right;
    text-decoration-color: white;
    background-color: ; 
    font-family: Lato;
    font-size: 20px;
    cursor: pointer;    
}
button{
    float: right;
}
button:focus{
    background:#FFD700;
}

You can use the native toggle method of the classList property. Also missing from your JavaScript is a reference to the clicked button .

 var button = document.querySelector('.btn-hold'); button.addEventListener('click', function() { this.classList.toggle('btn-alt-color'); if (button.getAttribute("data-text-swap") == button.innerHTML) { button.innerHTML = button.getAttribute("data-text-original"); } else { button.setAttribute("data-text-original", button.innerHTML); button.innerHTML = button.getAttribute("data-text-swap"); } }, false); 
 .btn-hold { float: right; text-decoration-color: white; background-color: ; font-family: Lato; font-size: 20px; cursor: pointer; } button { float: right; } button:focus { background: #FFD700; } .btn-hold.btn-alt-color { background-color: lightgreen; } 
 <button class="btn-hold" data-text-swap=" Starred!">Star Message!</button> 

jsFiddle

Please note that element.classList.toggle returns a Boolean value, no need to make things complicated :

 var button = document.querySelector('.btn-hold'), defaultButtonTxt = button.textContent; button.onclick = function() { this.textContent = (this.classList.toggle('btn-alt-color')) ? this.dataset.textSwap : defaultButtonTxt; } 
 button { float: right; } .btn-hold { float: right; text-decoration-color: white; background: #FFD700; font-family: Lato; font-size: 20px; cursor: pointer; } .btn-alt-color { background-color: lightgreen; } 
 <button class="btn-hold" data-text-swap=" Starred!">Star Message!</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM