In your WebServer module 2.2 in addition to the switch there is a “State” display that shows either ON or OFF. This is inserted into the HTML code by the Javascript snippet below:
if (state == “1”) {
document.getElementById(output).checked = true;
document.getElementById(output+”s”).innerHTML = “ON”;
}
else {
document.getElementById(output).checked = false;
document.getElementById(output+”s”).innerHTML = “OFF”;
}
Is there a way to insert a color tag so that “OFF” displays as (say) black and “ON” displays as (say) red? I tried adding style tags in front of the “ON” but that didn’t seem to work.
Thank you!
Hi.
You can change the color of an HTML element using JavaScript.
For example, look at the lines that I’ve inserted (in bold)
if (state == “1”) {
document.getElementById(output).checked = true;
document.getElementById(output+”s”).innerHTML = “ON”;
document.getElementById(output+"s").style.color = "red";
}
else {
document.getElementById(output).checked = false;
document.getElementById(output+”s”).innerHTML = “OFF”;
document.getElementById(output+"s").style.color = "black";
}
You also need to add something similar to the toggleCheckbox() function, like this:
function toggleCheckbox (element) {
var xhr = new XMLHttpRequest();
if (element.checked) {
xhr.open("GET", "/update?output="+element.id+"&state=1", true);
document.getElementById(element.id+"s").innerHTML = "ON";
document.getElementById(element.id+"s").style.color = "red";
}
else {
xhr.open("GET", "/update?output="+element.id+"&state=0", true);
document.getElementById(element.id+"s").innerHTML = "OFF";
document.getElementById(element.id+"s").style.color = "black";
}
xhr.send();
}
You can learn more about that in more detail here: https://www.w3schools.com/jsref/prop_html_style.asp
Let me know if this works for you.
Also, can you tell me how are you feeling about this new eBook? Is it easy to follow? Is there any topic that you would like to be covered in a future version?
Regards,
Sara
Awesome, Sara, that was easy! I’m certainly a novice at Javascript.
I love the new eBook on servers! I’ve been playing with the code you and Rui have posted on RNT for months but this book has really helped me understand what I was doing. And, despite the disclaimer that the book is not a tutorial on HTML, etc, it has wonderful, clear explanations that have really advanced my understanding of HTML and CSS.
Thank you for all the great tutorials you two have done. I’m a huge ESP8266/ESP32 fan and your website is my go-to reference. Keep up the great work!
Hi.
That’s great!
I’m really glad that you are enjoying the new eBook. We put a lot of effort to make things as clear as possible for beginners.
Thank you for the trust in our tutorials.
I’ll close this issue. If you need further help, you just need to open a new question in our forum.
Regards,
Sara