Switching from using the image ID to a class will allow for the opening of a modal from any of the six

In my project, I have a row of 6 different images that are randomly selected from an array of objects. Each object in the array contains both a thumbnail and a high-resolution image (which is the same as the thumbnail). The goal is to allow users to click on any of the thumbnails and view the full-screen high-res image in a modal. Currently, this functionality only works with the first image due to using the ID attribute. To make it work for all six images, I attempted to switch to using the class attribute but encountered issues. There are a total of 96 images in the array, with 48 thumbnails and 48 high-res images. Below is a snippet of the array, as well as abridged versions of the HTML, JavaScript, and CSS.

I've experimented with using both .avengerpic and avengerpic (the class name) but neither has provided the desired outcome. The objective remains to display 6 thumbnails in a row and enable users to open a modal displaying the larger high-res version of the chosen image upon clicking.

        
let picArray = [
     {thumbnail: "https://rcabrerapics.s3.us-east- 
     2.amazonaws.com/assets/avengers_1.jpg", image: 
     "https://rcabrerapics.s3.us-east- 
     2.amazonaws.com/assets/avengers_large_1.jpg"},
     ...
    {thumbnail: "https://rcabrerapics.s3.us-east- 
     2.amazonaws.com/assets/avengers_7.jpg", image: 
     "https://rcabrerapics.s3.us-east- 
     2.amazonaws.com/assets/avengers_large_7.jpg"}]

let moviePics = function() {
  document.querySelectorAll('.avengerPic').forEach(function(e) {
    const randomPic = Math.floor((Math.random() * picArray.length));
    e.src = picArray[randomPic].thumbnail;
  });
}

moviePics();

...

    
    <div class="container">
        <div class="pics">
            <table>
                <tr>
                    ... // Other HTML elements
                    <img class="avengerPic" id="myImg" src=...>
                    ... // Modal content

                    ... // Repeat for other images
              
                </tr>
            </table>
        </div>
    </div>
    
.container {
  display: flex;
  align-items: baseline;
  flex-direction: row;
  flex-wrap: nowrap;
  vertical-align: middle;
  margin: 5px 15px;
}

.pics img {...}
.modal {...}
.modal-content {...}
.caption {...}
.close {...}
  

Answer №1

const displayRandomAvengerPics = function() {
    document.querySelectorAll('.avengerPic').forEach(function(pic) {
        const randomIndex = Math.floor((Math.random() * picArray.length));
        pic.src = picArray[randomIndex].thumbnail;
    });
}

displayRandomAvengerPics();

const avengerImages= document.querySelectorAll(".avengerPic");    
const closeButtons = document.querySelectorAll(".close");
for (let i=0; i<avengerImages.length; i++){
    avengerImages[i].addEventListener('click', function(){
        let thumbnailSource = this.src;
        let fullImageSource;
        for(let j=0; j<picArray.length; j++){
           if (thumbnailSource == picArray[j].thumbnail){
               fullImageSource = picArray[j].image
           }
        }    
        this.nextElementSibling.style.display = "block";
        this.nextElementSibling.children[1].src = fullImageSource;
        this.nextElementSibling.children[2].innerHTML = this.alt;
     })
 }
for (let i=0; i<closeButtons.length; i++){
    closeButtons[i].addEventListener('click', function(){
        this.parentElement.style.display = "none";    
    })
}

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

Ensure that the div is styled with a white background and positioned next to another div with a right margin

I have a white-colored div that needs to be positioned next to another element on a webpage. Additionally, I need a paragraph placed on top of this div for information purposes. Please refer to the following link to see what I am trying to achieve: https:/ ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

How to use ng-click for a function in a directive with a custom template in Angular Material's $mdDialog?

In my project, I have utilized the $mdDialog.show() method within a custom directive to display a dialog with a custom template. This template includes two buttons - 'Cancel' and 'Confirm'. I am facing an issue with calling functions n ...

Unable to select selectbox in the bottom section of Safari browser

There seems to be an issue with the selectbox being unselectable at the lower part in Safari. It's difficult to pinpoint the exact problem in the code. You can see the issue on the country selectbox by visiting this website: <span> <sp ...

Having trouble finding routes when trying to pass a token as a parameter in Angular 5

Currently troubleshooting an issue where the route doesn't match when users click on the password reset link sent to their email. Strangely, the route works fine with alphabetical or string inputs. The route in question: {path: 'reset-password ...

Utilizing ReactJS and Plyr in tandem for Vimeo API Integration

I'm encountering an issue with my React component that utilizes the https://github.com/selz/plyr media player. Everything works as expected until I unmount the component, triggering an error from the Vimeo API. The specific error is: Uncaught (in prom ...

Endless loop JSON vulnerability

I recently came across a discussion on Stack Overflow about Google's practice of prepending while(1); to their JSON responses. Can anyone provide guidance on what type of PHP script would be suitable for this situation? I attempted the following: $ ...

Replicating a row in a table without disrupting a button within the row

As a novice in the world of coding, I am currently embarking on a project to revamp an existing website. The task at hand involves creating a table with a built-in save/edit feature, which I have successfully implemented. However, I am facing a roadblock w ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

Retrieve a value from an ArrayList that employs an external class

I am facing an issue with my ArrayList named results, which uses the ItemObjects class to store items. I am unable to extract a specific String from an item in results. The structure of the ItemObjects class is as follows: public class ItemObjects { ...

Adjusting the backdrop hues

My goal is to change the background colors of my website by cycling through all possible combinations. However, I'm encountering issues with my code and can't figure out what's wrong. var red = 0; var green = 0; var blue = 0; do { do ...

Should locator names be utilized in templates for the purpose of simplifying E2E tests?

When conducting deep nested tests, I often struggle to locate the items I need. Would it be unwise to use something like <h1 name="test-main-title">About Us</h1> and simply utilize element(by.name('test-main-title'));? Afterwards ...

What is causing the issue of blank options not being configured for ng-options inside a directive?

I am currently working on developing an AngularJS Directive for handling the prompts of a <select> input. There are 3 different modes that I am implementing: Disallowing a blank option This is the default mode Allowing a blank option with no text ...

When the parent DIV is hovered over, the image and text properties will be altered

Greetings, I am just starting out in web development and would like to seek guidance from the Stack Overflow community. Here is a link to my code: https://codepen.io/noxwon/pen/RwrmxKX My code is very basic and filled with repetitive lines. I have multip ...

The mesmerizing world of parallax animations and the smooth scrolling experience

I recently built a website using the SUPERSCROLLORAMA plugin, only to discover later that there are issues with parallax scrolling on iPad and iPhone. Now I'm trying to figure out how to solve this problem. It seems that events are disabled on these ...

Replace all instances of the same word with the word "and" using regular expressions

If we look at the sentence below: Blue shirt blue hat Can regular expressions be used to detect 2 matching words and replace the second one with and so it reads: Blue shirt and hat Now, let's tackle a more complex example. In this case, we nee ...

Is there a way to improve this code without the need for the variable `a`?

Assist in enhancing the performance of the functions below, without using the variable a getFieldsGroups(){ let list = []; if(this.activeTab.fieldsGroupName === ''){ this.activeTab = { groupIndex: 0, subgroupIndex: 0, f ...

Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using: function tblnewrow() { var newrow = ' ...

The chosen value in Select2 does not display in the order it was selected, but rather

I recently encountered an issue with a third-party plugin created by Ivan Vaynberg. When using the multiselect feature in select2, I noticed that the select2("val") method returns selected values in sorted order, rather than reflecting the order in which t ...