"Learn how to apply an addEventListener to querySelectorAll and retrieve the element's index, id, or value when it is

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.

Answer №1

If you want to locate the position of an element within an array while utilizing various array iteration methods, you can include additional parameters in your code (such as placing the index as the second parameter when using forEach):

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the moment when jQuery's load() function completes the loading of several images

My script utilizes jQuery's getScript() function to dynamically retrieve blog posts from Tumblr accounts. The response from the script is a JSON structure called tumblr_api_read, which includes image URLs among other things. function read(blogName) ...

Excessive CPU/GPU usage caused by CSS transition animations

I am currently working on a small element on my website that involves a random size change in one of the DOM elements. const theDiv = document.getElementById("the-div"); function animate(){ const value = Math.floor(Math.random() * 200); theDiv.sty ...

Is it possible to replace the catch function in JavaScript with a custom function?

Below is the code snippet: function xyz() { try { var a = someexecutions(); handlesuccess(a) } catch (err) { handleerror(err) } } This type of function is repeated numerous times in my codebase and I am looking for a way to improve it. f ...

Transmitting FormData from Angular to a .NET MVC Controller

Here's my perspective: <form ng-submit="onFormSubmit()"> <div class="form-group"> <label for="Movie_Genre">Genre</label> @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Na ...

leveraging AJAX to showcase information retrieved from a MySQL database

Hello! I am brand new to PHP and have little knowledge of AJAX. I am in the process of creating a photo gallery site and have used the following code to display my photos. I would like to make it possible, using AJAX or any other language, for someone to c ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...

Preserve identical elements within an array

I am looking to create an array of key:value pairs, even if there are duplicates present. My goal is to have an array of tasks, where each task consists of multiple operations. I only require the key/value for these operations. Currently, the value of th ...

Using jQuery to select and print the initial object from an array with multiple identical objects

I have a dataset structured as follows: var json.result= [ {"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"}, {"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"}, {"id":"2","category":"Camera","name":"7 ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Is it possible for a MUI control to automatically close itself when clicked outside of the component?

Currently diving into the world of MUI 5 component design. Does anyone know where I can locate the code responsible for closing a component when clicking outside of it? I've searched through the source code but couldn't pinpoint it. This functi ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...

Creating a dropdown navigation menu using CSS from href divs

I am working on a script that includes divs with images and href functions for clicking on them. <div class="home"><a href="index.php?pagina=home"></a></div> <div class="events"><a href="index.php?pagina=events"></a& ...

Always ensure that the full text is responsively aligned to the right of the image

.brand { font-size:1.2em; color:#777 !important; display:inline-block; vertical-align: middle; } .car { display:inline-block; vertical-align: middle; padding:5px 30px 0px 20px; } .car.img { margin:0 !important; width:100% ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

Navigating production mode in nuxtjs and uncovering errors

There seem to be numerous inquiries regarding this matter. Unfortunately, there doesn't appear to be a definitive solution. Is there any way to view detailed error logs in production mode? https://i.stack.imgur.com/prXUt.jpg ...

Ways to sum up the values within a JSON object

Currently, I am using an AJAX call to fetch JSON data from an API. My goal now is to add up all the visits. This is what I have implemented so far. Any suggestions on how I can achieve that? $(document).ready(function() { var X = []; var Y = []; var d ...

Linking Background Images in HTML

Is there anyone who can provide assistance with this question? I am looking for a solution where I can have a link with a background image, placed in a row within a table. Your help would be greatly appreciated. Thank you ...

How to verify for an empty array within a condition in JavaScript

I can't figure out why my conditional statement to handle the edge case of an empty input array is not working as expected. When I test it with my current example, it returns NaN (no clue why). However, if I change the conditional to if (array.length ...