marianna013 marianna013 - 7 months ago 24
Javascript Question

Changing html button with javascript

Been trying to crack this for days and I think I've got tunnel vision that can't see past my mistake!

I have an html button which when calling a javascript method and passing it true or false I want the button class to change as well as the innerHTML. Currently I can only get the class to change, see the code bellow!

var buttonHandler = function () {

toggleButton(false);
getRecords();
};

var btn = document.getElementById("get-records");
btn.addEventListener("click", buttonHandler);

function toggleButton (loaded) {

btn.innerHTML = loaded ? "Get next" : "Loading...";
btn.classList.toggle("button-not-loading");
btn.classList.toggle("button-loading");
}


The button html looks like this:

<button id="get-records" class="button-not-loading">Get next</button>
.button-loading { background-color:dodgerblue; color:white }
.button-not-loading { background-color:lawngreen; color:white }


Any help would be GREATLY appreciate!

Thanks!

M

Answer

You always pass false to your toggleButton function, thats why html is changed only once. You should change true/false also, just add variable which will hold this value:

var loading = true;

var buttonHandler = function () {
  loading = !loading;
  toggleButton(loading);
  getRecords();
};


var btn = document.getElementById("get-records");
btn.addEventListener("click", buttonHandler);

function toggleButton (loaded) {
   btn.innerHTML = loaded ? "Get next" : "Loading...";
   btn.classList.toggle("button-not-loading");
   btn.classList.toggle("button-loading");
}
.button-loading { background-color:dodgerblue; color:white }
.button-not-loading { background-color:lawngreen; color:white }
<button id="get-records" class="button-not-loading">Get next</button>