This code is a demonstration of two features, the checkboxes and the radios. A black-bordered box appears with two ways for you to change its style. Check on the checkbox to change the border to a 5px solid purple, uncheck it to go back to its initial 1px solid black. Use the radio buttons to change the background color of the box to either red, green or blue.
Pay special attention to the radio buttons. Red is set to "checked", meaning the box's color should have been set to red by default upon opening or refreshing this ask page, but it's not. Instead, there is no color, and in order to make the box turn red, you have to force it by clicking on the red radio dial. Compare that to the checkbox input, where the behavior of toggling between checked and unchecked parameters works as intended.
I've always thought that whatever item is labelled "checked" is automatically active, provided the check declarations are made within your Javascript. In the border checkbox toggle example (see border.addEventListener), the original fallback option was set to "initial," and in this case the box would go back to its 1px solid black style. However, the "initial" keyword did not work, for the entire border disappeared during my test, so I had to explicitly state "1px solid black" in that same line as an insurance measure.
My initial question was on why the "checked" feature works better on checkboxes instead of radios, but to be blunt, I need a better grasp on how the "checked" feature works when it comes to Javascript. How do I rewrite this code so that when I open this web page, the box will have automatically changed color to whatever value was set? If red was "checked", the box is already red, and so on.
function changeBorder() { const monitor = document.querySelector(".Screen"); const border = document.getElementById("ScreenBorder"); border.addEventListener("change", () => { border.checked ? monitor.style.border = "5px solid purple" : monitor.style.border = "1px solid black"; }); } function changeBG() { const screen = document.querySelector(".Screen"); const screenbackground = document.querySelectorAll('INPUT[name="r"]'); screenbackground.forEach(radio => { radio.addEventListener('click', () => { const bgColor = radio.value; screen.style.background = bgColor; }); }); } changeBorder(); changeBG(); DIV.Screen { border: 1px solid black; width: 256px; height: 256px; } <DIV class="Screen"></DIV> <P> <INPUT type="radio" name="r" value="red" checked>Red <INPUT type="radio" name="r" value="blue">Blue <INPUT type="radio" name="r" value="green">Green </P> <P><INPUT id="ScreenBorder" type="checkbox" name="checkbox" />Violet Border</P>