0

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 below:

var buttonHandler = function () {
  toggleButton(false);
  getRecords();
};

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

JS:

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

HTML (The button looks like this):

<button id="get-records" class="button-not-loading">Get next</button>

CSS: .button-loading { background-color:dodgerblue; color:white }

.button-not-loading { 
   background-color:lawngreen; 
   color:white 
}

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer! In practice, of course, make sure you name the global variables in a way that make sense. 'loading' is a very generic name that could conflict with other toggle buttons.
1

Instead of toggleButton(false);
Use this toggleButton(this.classList.contains('button-not-loading') ? false : true);

1 Comment

I personally like this solution over the use of a global variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.