I have some js that changed background images based on what radio button is selected, but I feel like this is a "dirty" way of doing it. Is there a better way to write this for better functionality? Maybe even do it in pure CSS?
<input
id="main-checkbox-1"
type="radio"
class="main-container__checkbox"
name="main"
value="first"
checked
/>
<label for="main-checkbox-1" class="main-container__checkbox-label"
> </label
>
<input
id="main-checkbox-2"
type="radio"
class="main-container__checkbox"
name="main"
value="second"
/>
<label for="main-checkbox-2" class="main-container__checkbox-label"
> </label
>
<input
id="main-checkbox-3"
type="radio"
class="main-container__checkbox"
name="main"
value="third"
/>
<label for="main-checkbox-3" class="main-container__checkbox-label"
> </label
>
document.querySelectorAll(".main-container__checkbox").forEach((item) => {
item.addEventListener("click", function () {
if (item.checked && item.getAttribute("value") == "first") {
document.querySelector(".main-container").style.backgroundImage =
"url(../img/main3.jpg)";
}
if (item.checked && item.getAttribute("value") == "second") {
document.querySelector(".main-container").style.backgroundImage =
"url(../img/main.jpg)";
}
if (item.checked && item.getAttribute("value") == "third") {
document.querySelector(".main-container").style.backgroundImage =
"url(../img/main2.jpg)";
}
});
});