Hi. Just trying to toggle a switch to change the background colour from ‘none’ to ‘yellow’. any ideas why my code isn’t working would be appreciated. thanks.
Can you show us your code so far and maybe the html page as well? It’d be nice to know what your code looks like and what you’ve been trying to do so far.
Oh sorry yes I completely forgot to post the link to the code.
<button id='switch' onclick='toggleSwitch'>
Okay looking at your HTML first. You forgot to supply the id of the bulb top to your function. Even in callbacks you need to apply parameters.
Going around to your JS
function toggleSwitch(bulb_top) {
var lightbulbColour = document.getElementById(bulb_top).style.backgroundColor;
if(lightbulbColour == 'none') {
document.getElementById(bulb_top).style.backgroundColour = 'yellow';
}
else {
document.getElementById(bulb_top).style.backgroundColour = 'none';
}
}
While it is expected for lightbulbColour
to be equal “none”, it’s an empty string when the web page first starts up. It’s going to need to be changed in both places.
Lastly document.getElementById(bulb_top).style.backgroundColour
should be document.getElementById(bulb_top).style.backgroundColor
.
Hope this helps. If any of this unclear or confusing, please let me know and I will try to help.
thankyou. I think i’ve corrected most of the javascript with your help
function toggleSwitch(lightbulbColour, bulb_top) {
var lightbulbColour = document.getElementById('bulb_top').style.backgroundColor = 'none';
if(lightbulbColour === 'none') {
lightbulbColour = document.getElementById('bulb_top').style.backgroundColor = 'orange';
}
else if(lightbulbColour !== 'none') {
lightbulbColour = document.getElementById('bulb_top').style.backgroundColor = 'none';
}
}
and added the following css to the bulb_top
background-color: none;
The code now turns the bulb orange on first click but does not turn back to ‘none’ or toggle onclick. Any help would be appreciated
Every time toggleSwitch
runs you are setting lightbulbColour
to none
.
If you just need to toggle the color I would suggest using a CSS class and the classList.toggle()
method.
<button>Toggle color</button>
.btn-color {
background-color: orange;
}
document.querySelector("button").addEventListener("click", ({ target }) => {
target.classList.toggle("btn-color");
});
Struggling to see why the suedo element :checked doesn’t work either? The code is pretty basic.
#checkbox:checked ~ .bulb_top {
background-color: yellow;
}
The tilde only works if the two elements share the same parent.
You can use the :has selector, just know it is still a fairly new selector. You can check the browser compatibility section.
body:has(input[type='checkbox']:checked) .bulb_top {
background-color: yellow !important;
}
thank you that works perfectly
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.