Whenever I press the view button, all the cards open instead of just the one I chose from the index. Can anyone tell me where I am going wrong?

I've encountered an issue with the View buttons I added to display more detailed information about the characters in the card bodies. When I click on the view button, it opens all the boxes instead of the one I selected. I've tried using a for loop instead of forEach, but then only the first card body opens. The console.log(event.target) correctly shows the buttons, but they all reference the card body at index 0. What am I doing wrong?


                    // JavaScript code goes here
                

                    /* CSS code goes here */
                

                    <!-- HTML code goes here -->
                

Answer №1

Calling document.querySelectorAll(...) retrieves all matching elements across the entire document, resulting in the display of all info boxes after clicking the "View" button.

function showInfos(e){
    
    /* Open view buttons */
    let showdetails = document.querySelectorAll('.showdetails');

    showdetails.forEach((showdetail,index) =>{
        showdetail.style.display = 'block'
    });
}

To simplify the code:

function showInfos(e) {
    const showdetails = e.target.querySelector('.showdetails');
    showdetails.style.display = 'block';
}   

This code references the clicked element (the button) and executes the query on that specific element.

Example with full functionality

const getAgent = async() =>{
    let url = 'https://valorant-api.com/v1/agents'
    let res = await fetch(url);
    let data = await res.json()
    createAgentBox(data);
   
}

const createAgentBox = (element) =>{

    const agentContainer  = document.querySelector('.agent-container');
    
    let agents = element.data; 
    
    agents.forEach(agent =>{
        
        let agentName = agent.displayName;
        let agentImage = agent.fullPortrait;
        let desc = agent.description;
        let abilitiesImage1 = agent.abilities[0].displayIcon;
        let abilitiesImage2 = agent.abilities[1].displayIcon;
        let abilitiesImage3 = agent.abilities[2].displayIcon;
        let abilitiesImage4 = agent.abilities[3].displayIcon;
        let abilitiesName1 =  agent.abilities[0].displayName;
        let abilitiesName2 =  agent.abilities[1].displayName;
        let abilitiesName3 =  agent.abilities[2].displayName;
        let abilitiesName4 =  agent.abilities[3].displayName;

        let x = `<div class="agentbox">
        <img src=${agentImage} alt="">
        <h1 class='agentname'>${agentName}</h1>
    
        <button class="seeDetails" >View
            <div class="showdetails"  >
                <i class="fa-solid fa-xmark"></i>
                        <p>${desc}</p>
                    <div class='boxs'>
                        <div class="box1">
                            <img src=${abilitiesImage1} alt="">
                            <p>${abilitiesName1}</p>
                        </div>
                        <div class="box2">
                            <img src=${abilitiesImage2} alt="">
                            <p>${abilitiesName2}</p>
                        </div>
                        <div class="box3">
                            <img src=${abilitiesImage3} alt="">
                            <p>${abilitiesName3}</p>
                        </div>
                        <div class="box4">
                            <img src=${abilitiesImage4} alt="">
                            <p>${abilitiesName4}</p>
                        </div>
                    </div>    
                    </div>
                </div>
            
            </button>
             
        
    </div>`
   
        

    agentContainer.innerHTML += x;  

    });   

    let seeDetails = document.querySelectorAll('.seeDetails')

    seeDetails.forEach(seeDetail =>{
        seeDetail.addEventListener('click', showInfos)
    })
    
    function showInfos(e) {
        const showdetails = e.target.querySelector('.showdetails');
        showdetails.style.display = 'block';
    }   
 }

getAgent()


let searcInput = document.querySelector('.searchbox');


searcInput.addEventListener('input',function(){
    const agentsName = document.querySelectorAll('.agentname')
    let container  = document.querySelector('.container')
    
    const search = searcInput.value;
    

    agentsName.forEach((agentName) =>{
        agentName.parentElement.style.display = 'block';
        container.style.height = '100%'
        if(!agentName.innerHTML.toLowerCase().includes(search)){
            agentName.parentElement.style.display = 'none';
            container.style.height = "100vh"
        }
    })
    
})
@import url("https://fonts.googleapis.com/css2?family=Audiowide&display=swap");
... (CSS styles)

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

Slide inside a div to move content

Check out the script I've been experimenting with for bringing in a menu from the left: Demo Fiddle To make this work, the sliding DIV needs to not only appear on the left but also push the 'left panel' and 'right panel' accordin ...

Creating a grid in JavaScript using a formula

I'm looking to create a grid of objects using JavaScript. Unfortunately, I can't remember the formula and I haven't been able to find it online: var width = 113; var height = 113; var col = 10; ...

After the submit button is disabled, the form fails to be submitted

Hello, I am having an issue with disabling my button after the form is submitted. The button gets disabled, but the PHP code does not execute. I have tried various scripts from the internet, but they all seem to have the same result: the button gets disab ...

Transferring an HTML file to a destination stream

Currently, I'm in the process of constructing a proxy server. One of the tasks I'm tackling involves blocking specific URLs. I have developed a simple HTML page that is supposed to display whenever a blocked URL is requested, but unfortunately, ...

There was an error thrown: [vuex] getters must be defined as a function, however, the getter "getters.default" is an empty

After building my VUE project for production with NPM, I encountered an error in the console. Can anyone shed some light on why vuex is presenting this complaint? npm 3.10 , node.js 8.11 Uncaught Error: [vuex] getters should be function but "getters.defau ...

Raspberry Pi 4: My LED is only blinking 8 times instead of the expected 16 times

I have encountered an issue with my program run, compilation, and result. In the screenshot below, you can see that my LED is only blinking 8 times instead of the anticipated 16 times. My expectation was for the LED to blink every 0.25 seconds for a total ...

Show a grid layout with adjustable sizing and elements centered in the middle

When dealing with a layout like the one below, how can we ensure that elements are centered within the wrap container? The margins around the elements should be flexible but at least 14px. .wrap{ display: grid; grid-template-columns: repeat(auto-fi ...

Disabling the camera feed in a React application

Attempting to turn off the webcam using javaScript in React has been a bit challenging. Whenever I shift to a new component or when a component is destroyed, my react component immediately moves to the next page, but the webcam light remains on in the new ...

What is the formula to determine the sizes of grandchildren div containers?

Hey everyone, I'm having some trouble with my jQuery code and I can't seem to figure out what's going on. Here's the scenario: I'm creating a few divs (based on entries from MySQL) and I'd like to show you the end result: ...

Utilize the power of Javascript/AJAX or jQuery to submit multiple forms simultaneously

I am currently working on a project which involves having 3 forms on a single page. The reason behind this is that one of the forms is displayed in a modal dialog. My goal is to allow users to submit all 3 forms with a single button click, and I also wan ...

Problem with AJAX updating CSS class

My HTML table features a column that displays a Yes/No option. When a user switches the option from Yes to No or vice versa, it triggers an AJAX call to a PHP script which updates the corresponding record in the database. Everything is functioning correctl ...

Maintaining alignment between the site content and the navbar items is a key feature of Bootstrap

I am struggling to align the brand and dropdown menu on the right with the content of my page. My goal is to have a single column for the content, taking up col-8 on larger devices and col-12 on smaller devices. I want the navbar and footer to always be 10 ...

What is the best way to display PHP files as the main landing page on my Express server?

I am currently using php for my home page, but I have come to realize that Node.js does not support .php files. So, I'm looking for a solution on how to address this issue. Below is the code I am using: var app = require('express')(); var h ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Disarrayed image in absolute position on my webpage

I have a website with an auto-resizing background, but I am struggling to have a fixed black bar at the bottom of the page. Everything looks good when the browser window is maximized, but as soon as you scale it down and start scrolling, the black bar alm ...

Use Flexbox hover effect to display submenu text exclusively in the column being hovered

Having an issue with a 5 column flexbox. Each box should display a header text and supplementary text only when hovered over, returning to normal when unhovered. I was able to accomplish this in Codepen (view the rough model here). However, when trying to ...

I am looking to update my dexie values from null to empty strings

I am facing an issue where the data-table values with null entries need to be replaced with empty strings. There are instances when the department value is empty, resulting in null entries in the data tables. db = db_open(); db.fuel.toArray().then(fuel = ...

Export data table from HTML to Excel successfully implemented with C#

I am currently working on an Umbraco website and developing a custom plugin for the backend that allows users to export an Excel worksheet from an HTML table. In order to achieve this functionality, I am utilizing AngularJS along with a C# controller. Belo ...

tips on launching a pre-existing react native project

Trying to run a project downloaded from someone else can be quite challenging. I encountered some issues where the project just wouldn't start, and now I'm completely stuck. Can anyone help me out? https://github.com/sunlight3d/react_native_v0.4 ...

Do you think it's essential to utilize express for node in developing moderate-sized applications?

What is the best approach for handling cookies and authentication in a project with approximately 30 or 40 routes? Is it feasible to manage cookies and authentication without using Express? What percentage of developers prefer using Express over bare bon ...