How to addEventListener to querySelectorAll and when triggered get element index(or id, value)?

Viewed 931

I'm making background selector in site menu, It will change backgroundImage when user clicks on spec. image (that triggers radio button). I want to do it using querySelectorAll(".selected"), loop it and set addEventListener(click, ..) get index(or id, value) and set backgroundImage using background_list array.

Menu Image

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 example I have dozens of images

document.querySelectorAll(".select").forEach( item => {
      item.addEventListener('click', arrow => {
      document.body.style.backgroundImage = `url("${background_list[index]}")`
    })})

Is there any way to find triggered index(id or value)? And how would you implement code for this, what's easiest solution? I'm beginner in JS

1 Answers

You can find the index of an element in an array while using these array iteration functions by adding extra parameters (index is the second parameter with forEach):

document.querySelectorAll(".select").forEach((item, index) => { // here
      item.addEventListener('click', arrow => {
      document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
Related