Reputation: 3
I'm trying to display ON and OFF of the CSS part of the code based on the value given in the database. What I want to know is how do I edit the content of the CSS below (.switch-button:before) to change it to ON or OFF.
I've tried giving each element an ID and using document.getElementById for it but it still doesn't work.
The Circled part is what I want to change based on the database value. Currently, its default (the content in CSS) is set to "OFF".
CSS
.switch-button:before {
content: "OFF";
color: #ffffff;
position: absolute;
top: 0;
bottom: 0;
right: 0;
width: 60px;
display: flex;
align-items: center;
justify-content: center;
z-index: 3;
pointer-events: none;
}
HTML
<div id="turned_onclass" class="turned_onclass" style="display: none;">
<center><label><u>On/Off</u></label></center>
<div class="switch-button">
<input class="switch-button-checkbox" type="checkbox"></input>
<label class="switch-button-label" for=""> <span id="turned_onspan" value="<%= devices.turned_on %>" class="switch-button-label-span">ON</span> </label>
</div>
</div>
Javascript
<script>
/* Button Displays ON/OFF depending on Value */
var turned_onTypeDocument = document.getElementById("turned_onspan");
var turned_onType = turned_onTypeDocument.getAttribute("value");
if (turned_onType == 1) {
document.getElementById("turned_onspan").innerHTML = "ON";
document.getElementById("turned_onspan").style.content = "OFF";
}
if (turned_onType == 0) {
document.getElementById("turned_onspan").innerHTML = "OFF";
var turned_onClassContent = document.getElementsByClassName("switch-button-label-span");
turned_onClassContent.style.content = "ON";
}
///////////////////////////////////////////////
</script>
Upvotes: 0
Views: 166
Reputation: 370669
While it's possible to dynamically change CSS, a better approach would be to just set up the initial rules properly. For example, you could toggle a class to produce a new :before
content.
.switch-button:before {
content: "OFF";
color: #ffffff;
....
}
.switch-button.on:before {
content: "ON";
}
And then just do
for (const input of document.querySelectorAll('.switch-button-checkbox')) {
input.addEventListener('change', (e) => {
input.parentElement.classList.toggle('on', e.checked);
});
}
for (const input of document.querySelectorAll('.switch-button-checkbox')) {
input.addEventListener('change', (e) => {
input.parentElement.classList.toggle('on', e.checked);
});
}
.switch-button:before {
content: "OFF";
}
.switch-button.on:before {
content: "ON";
}
<div class="switch-button">
<input class="switch-button-checkbox" type="checkbox">
</div>
Upvotes: 1