I'm working on a background selector for my site's menu. The goal is to change the background image when a user clicks on a specific image that triggers a radio button. I plan to achieve this using querySelectorAll(".selected"), looping through it, adding an event listener (click), getting the index (or id, value), and setting the background image using an array called background_list.
https://i.sstatic.net/MCp68.png
var background_list = ["/images/air-balloon.jpg","/images/mary-christmas.jpg","/images/mountain.jpg","/images/panorama.jpg","/images/plants.jpg","/images/sunset-mountain.jpg","/images/underwater-star.jpg","/images/vinyl-player.jpg"...]
<div class="dropdown-background-container">
<div>
<input
type="radio"
id="image-1"
class="select"
value="1"
>
<label for="image-1">
<img src="/images/air-balloon-small.jpg" alt="Air Balloons">
</label>
</div>
<div>
<input
type="radio"
id="image-2"
class="select"
value="2"
>
<label for="image-2">
<img src="/images/mary-christmas-small.jpg" alt="Mary Christmas">
</label>
</div>
For instance, I have numerous images like these.
document.querySelectorAll(".select").forEach( item => {
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
Is there a way to identify the triggered index (id or value)? How would you go about implementing this code? What's the simplest solution? I'm new to JS.