show the most up-to-date data in the array upon selecting a particular element

I'm working on a project with an array of objects representing different pets. Each pet card should display specific information about the pet when clicked, but I'm struggling to make only the relevant information show up. How can I achieve this functionality?

const pets = [
    {
      "name": "Jennifer",
      "img": "../../assets/images/pets-jennifer.png",
      "type": "/",
    },
    {
      "name": "Sophia",
      "img": "../../assets/images/pets-sophia.png",
      "type": "/",
    },
    {
      "name": "Woody",
      "img": "../../assets/images/pets-woody.png",
      "type": "..",
    }
]
document.querySelectorAll('.pet_card').forEach(card => card.addEventListener('click', () => {
    modal.classList.add('show-modal')
})) 
document.querySelector('.modal').innerHTML = `
    ${pets.map(petTemplate).join('')}
`;
function petTemplate(pet) {
    return `
        <div class="modal_wrap">
            <div class="modal_img">
                <img src="${pet.img}">
            </div>
            <div class="modal_content">
                <h3>${pet.name}</h3>
            </div>
        </div>
    `;
}
<div class="main_pets_wrap">
  <div class="pet_card">
    <h5>Woody</h5>
    <button class="pet_card_btn">Learn more</button>
  </div>
  <div class="pet_card">
    <h5>Jennifer</h5>
    <button class="pet_card_btn">Learn more</button>
  </div>
  .....
</div>

Answer №1

Below is the solution I came up with:

<!-- Insert this div element -->
<div class="popup"></div>
// Convert node list to array using spread operator
[...document.querySelectorAll('.pet_card')].forEach(card =>
    card.addEventListener('click', (event) => {
       let pet = getSelectedPet(event.target);
       let popup = createPopup(pet);
       document.querySelector(".popup").innerHTML = popup;
}));

// Function to find selected pet information
function getSelectedPet(button) {
  let name = button.querySelector("h5").innerText;
  return pets.find(pet => pet.name == name);
}

// Template function for generating pet details in a modal
function createPopup(pet) {
    return `
        <div class="popup_wrapper">
            <div class="popup_image">
                <img src="${pet.img}">
            </div>
            <div class="popup_content">
                <h3>${pet.name}</h3>
            </div>
        </div>
    `;
}

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

Obtain an Array Containing all Current Page Paths in Gatsby

While creating a custom `404` page in Gatsby, I am looking to provide users with recommended similar path names based on the non-existent path they have accessed. Can anyone guide me on how to retrieve an array of all the current pages on my website? ...

Integration of a QR code scanner on a WordPress website page

I'm in the process of setting up a QR code scanner on my Wordpress site or within a popup. The goal is for users to be able to scan a QR code when they visit the page/popup link. Specifically, the QR code will represent a WooCommerce product URL, and ...

Changing the color of a selected list element using an Angular directive

I'm currently facing an issue with my directive that is supposed to turn a list element red when clicked. It works fine, but I also want it to revert back to black when another list item is selected, so only one item stays in red color. Here is how I ...

Generating a highchart by retrieving JSON data using AJAX

I'm currently working on generating a basic chart on a webpage using data from a MySQL database that is fetched via a MySQL script. My main challenge lies in understanding how to combine the ajax call with the necessary data for the chart. I'm n ...

Encounter error message "Angular-CLI: Karma-Webpack fails due to 'file or directory not found'"

After initially starting with the classic Angular/systemjs setup for the Tour of Heroes, I transitioned to using angular-client. The application now performs well in both development and production modes, except for when I try to run tests using ng test. A ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

Checkbox no longer has an underline when it is checked

My goal is to develop a Todolist app using express.js and node.js. The idea is that when a user checks a checkbox for a task, that specific data in the array should be underlined. However, this feature is not working when I try to implement it via HTTP pos ...

When formatting amounts, it is important to not allow the thousand separator to come after the decimal separator

I am tasked with ensuring that a thousand separator does not come after a decimal separator every time a key is pressed. Is it feasible to achieve this using regular expressions? If so, can you explain how? ...

Retrieve the latest entry from a JSON file containing epoch timestamps

Currently, I am in the process of developing an app using angularjs. In my json data, I have timestamps and corresponding values like below: { "dps": { "1455719820": 0, "1455720150": 0, "1455720480": 0, "1455720810": 0, " ...

Encountering an issue when attempting to construct the project: it asks for callback functions, but instead received an [

I'm currently facing an issue while trying to access a function that is crucial for updating some database values. Whenever I attempt to build the project, I encounter the following error: Error: Route.post() requires callback functions but got a [ ...

The error message "The function XXX.isSupported is not defined" is displayed

Integrating a JavaScript library into Typescript When I use this function in JavaScript, it works perfectly: _clickHandler() { TouchID.isSupported() .then(authenticate) .catch(error => { AlertIOS.alert('TouchID not supported'); }); ...

What is preventing the X-Powered-By Header from being disabled even after implementing helmet security measures?

After incorporating Helmet into my Express application and configuring it in app.js with the following code: app.use(helmet()); const helmet = require('helmet'); Upon restarting the app, the X-Powered-by header is still enabled despite using app ...

Is there a way to identify when a specific DIV element changes its dimensions without continuously polling for updates? In other words, I am looking for a method to

Running ads on my website has been great, but one of the ads keeps changing the dimensions of the DIV it's in, causing layout issues with other elements on the page. To solve this problem, I need to add an event listener to the specific DIV element t ...

Is it possible to invoke a JavaScript function from within a CSS file?

Currently, I am focusing on developing responsive web design and looking for ways to avoid creating multiple versions of each page based on screen width variations. The struggle lies in managing font sizes effectively. While attempting to style them using ...

substitute the character ""<0x00>"" within the given string

I'm currently facing an issue with a string I received after sending a command line that included the <0x00> character. How can I remove it from the string? For instance, here is my variable string: <0x00> awplus # desired output: awplus ...

Design incisions on Cylinder Structure

I am facing a challenge while attempting to replicate a scene. The specific detail I am struggling with is quite intricate. The scene features a surface made of cylinder geometry with numerous small circular notches. Inside these notches, there are white ...

Troubleshoot Nested Array URL Parameter Problems in Node.js

I am encountering an issue with extracting data from an array that I am sending to my API through an AXIOS call to Express. The call is sent successfully, but the issue arises when trying to access the data in the property_features parameter. Even though m ...

Guidelines on concealing the parent component while the child component is loading in Angular 2

In my latest project, the view setup is as follows: https://i.sstatic.net/VxJ9U.png Upon page load, the Parent Item Description should be visible while the Selected sub item description remains hidden. When a Sub Item x is selected, the Parent Item Desc ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

JavaScript enables users to store over 5 megabytes of data on their client devices

Is there a way to store more than 5mb in the client browser? I need this functionality across various browsers including Firefox, Chrome, Internet Explorer, Safari (iOS), and Windows Phone 8 Browser. Initially, localStorage seemed like a viable option as i ...