Joseph Romero
Joseph Romero

Reputation: 55

How to change text and color of a button when it is clicked using Javascript/HTML only

I need to be able to change the a button color and text to something other than the default.

<button id="partyTimeButton">Party Time!</button>

JS

var partyEvent = function()
{
    if (partyBtn < 0) 
    {
        partyBtn = new Date().getHours(); 
        partyBtn = "Party Over";

      // text in the button should read "Party Over"
        // color of the button should be "#0A8DAB" (bonus!)
    }

    else
    {
        partyBtn = -1;
        partyBtn = "PARTY TIME!"; 
        // text in the button should read "PARTY TIME!"
        // color of the button should be "#222" (bonus!)
    }
};

partyBtn.addEventListener("click", partyEvent);

Upvotes: 0

Views: 48

Answers (1)

Sreekanth
Sreekanth

Reputation: 3130

Your code snippet has some issues with the way you defined variables and text. PartyBtn is updated as -1 and "Party time!" and as hours number and "Party Over" , one after the other, which I think, shouldn't be.

Updated the snippet with some formatting and variables declarations. Hope this should get you going.

var partyBtn = document.querySelector("#partyTimeButton");
var partyBtnCount = -1;

var partyEvent = function() {
  console.log(partyBtnCount);
  if (partyBtnCount < 0) {
    partyBtnCount = new Date().getHours();
    partyBtn.innerHTML = "Party Over";
    partyBtn.style.color = "#0A8DAB"
      // text in the button should read "Party Over"
      // color of the button should be "#0A8DAB" (bonus!)
  } else {
    partyBtnCount = -1;
    partyBtn.innerHTML = "PARTY TIME!";
    partyBtn.style.color = ""
      // text in the button should read "PARTY TIME!"
      // color of the button should be "#222" (bonus!)
  }
};

partyBtn.addEventListener("click", partyEvent);
<button id="partyTimeButton">Party Time!</button>

Upvotes: 1

Related Questions