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
}
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>
Instead of toggleButton(false);
Use this toggleButton(this.classList.contains('button-not-loading') ? false : true);
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.