the pop-up window consistently shows identical information

I have coded a popup feature that should display different details for each product when the user clicks on a button. However, I am facing an issue where no matter which button is clicked, the popup always shows the details of the last product. Can anyone provide insights on why this might be happening?

CSS Code:

.cards {
    overflow: auto;
    white-space: nowrap;
    margin-top: 10px;
}

.options a {
    margin-left: 10px;
    text-decoration: none;
}

.card {
    display: inline-block;
    margin: 5px;
    height: 200px;
}
/* Additional CSS properties */

JS Code:

function showpopup(params) {
    // JavaScript function logic
}
function hidepopup(params) {
    // JavaScript function logic
}
/* Additional JavaScript functions */

HTML Markup:

<div class="container-full" id="container">
    <div class="product-cards">
        <!-- HTML markup for product cards and buttons -->
    </div>
    <div class="product-popups">
        <!-- HTML markup for popups with product details -->
    </div>
</div>
</div>

If you have any suggestions or solutions to fix this issue, please share them!

Answer №1

There are some key errors in your code:

Firstly, you have defined "params" as an argument for your functions but have not utilized it.

Secondly, there are multiple tags with the same id in your HTML, which is invalid as per HTML standards. Each id should be unique.

Lastly, the reason only the last popup is being displayed is because of the for-loop inside your function. This causes the loop to iterate over all tags with the specified class and display the final one. You can avoid using a for-loop by utilizing the "params" argument to assign ids to the pop-up windows. Here is an example code snippet:

function showpopup(params) {
        var card= document.getElementsByClassName('card');
        var popup;

        popup=document.getElementById(params);
        popup.style.display='block';
      }
      
      function hidepopup(params) {
        var card= document.getElementsByClassName('card');
        var popup;
        
        popup=document.getElementById(params);       
        popup.style.display= 'none';
      }
.cards {overflow: auto;white-space: nowrap;margin-top: 10px;}
    .options a {margin-left: 10px;text-decoration: none;}
    .card {display: inline-block;margin: 5px; height: 200px ;}
    .bgimg {height:410px;}
    .scm a {text-decoration: none;}
    .fb:hover {color:#4267B2}
    .insta:hover {color: #FD1D1D;}
    .gm:hover {color: #B23121;}
    .centring {margin: auto; display: flex;justify-content: center; align-items: center;}
    
    .popup-hide { position: fixed;
    padding: 5px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) ;
    transition: 100ms ease-in-out;
    border: 1px solid black;
    border-radius: 10px;
    z-index: 10;
    background-color: white;
    width: 800px;
    max-width: 80%;
     display: none;}
     
    .popup-show { position: fixed;
    padding: 5px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) ;
    transition: 100ms ease-in-out;
    border: 1px solid black;
    border-radius: 10px;
    z-index: 10;
    background-color:white;   
    width: 800px;
    max-width: 80%;
   display: block;}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>pop-up</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
   
   <div class="container-full" id="container">
      <div class="product-cards">
        <div class="card" style="width:250px;height: 200px;">
          <img class="card-img-top" src="1.jpg" alt="Card image">
          <div class="card-body">
            <button class="btn btn-primary" id="showpopup" onclick="showpopup('pop1')">Open</button>
          </div>
        </div>
        <div class="card" style="width:250px;height: 200px;">
          <img class="card-img-top" src="2.jpg" alt="Card image">
          <div class="card-body">
            <button class="btn btn-primary" id="showpopup" onclick="showpopup('pop2')">Open</button>
          </div>
        </div>
      
      </div>
      <div class="product-popups">
        <div class="popup-hide" id="pop1"> 
          <button class="btn btn-primary" id="hidepopup" onclick="hidepopup('pop1')">&times;</button>
          <hr>
          <div class="row">
            <div class="col-sm-4">
              
              <img style="width: 200px;max-width: 90%;" src="1.jpg" alt="">
            </div>
            <div class="col-sm-8">
              
              price:200DA <br>
              <br><br>
            </div>
          </div>
        
        </div>
        <div class="popup-hide" id="pop2"> 
          <button class="btn btn-primary" id="hidepopup" onclick="hidepopup('pop2')">&times;</button>
          <hr>
          <div class="row">
            <div class="col-sm-4">
            
              <img style="width: 200px;max-width: 90%;" src="2.jpg" alt="">
            </div>
            <div class="col-sm-8">
              
              price:300DA <br>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Deleniti, molestiae totam aliquam 
              quas optio praesentium! Soluta id ea est maxime laudantium, iure voluptatibus voluptatum et nemo modi reprehenderit bea
              tae. Dolorum?
              <br><br>
            </div>
          </div>
        
       _
       </div>
      </div>

    <script src="javascript.js"></script>
</body>
</html>

Answer №2

Your JavaScript code has been revamped, now making use of the `forEach()` method for better logic implementation. Moreover, function calls have been eliminated from the HTML structure.

var popup = document.querySelectorAll('.popup');
var btn = document.querySelectorAll('.card-body button');
var btn_close = document.querySelectorAll('.popup-hide.popup button');

Array.from(btn).forEach(function(btnArray, i) {
    btnArray.addEventListener('click', function() {
        popup[i].style.display = 'block';  
    });
});

Array.from(btn_close).forEach(function(btn_closeArray, i) {
    btn_closeArray.addEventListener('click', function() {
        popup[i].style.display = 'none';  
    });
});
.cards {overflow: auto;white-space: nowrap;margin-top: 10px;}
.options a {margin-left: 10px;text-decoration: none;}
.card {display: inline-block;margin: 5px; height: 200px ;}
.bgimg {height:410px;}
.scm a {text-decoration: none;}
.fb:hover {color:#4267B2}
.insta:hover {color: #FD1D1D;}
.gm:hover {color: #B23121;}
.centring {margin: auto; display: flex;justify-content: center; align-items: center;}

.popup-hide { position: fixed;
padding: 5px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) ;
transition: 100ms ease-in-out;
border: 1px solid black;
border-radius: 10px;
z-index: 10;
background-color:white;   
width: 800px;
max-width: 80%;
display: none;}
.popup-show { position: fixed;
padding: 5px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) ;
transition: 100ms ease-in-out;
border: 1px solid black;
border-radius: 10px;
z-index: 10;
background-color:white;   
width: 800px;
max-width: 80%;
display: block;}
<div class="container-full" id="container">
<div class="product-cards>
<div class="card" style="width:250px;height: 200px;">
<img class="card-img-top" src="1.jpg" alt="Card image">
<div class="card-body">
<button class="btn btn-primary" id="showpopup">Open</button>
</div>
</div>
<div class="card" style="width:250px;height: 200px;">
<img class="card-img-top" src="2.jpg" alt="Card image">
<div class="card-body">
<button class="btn btn-primary" id="showpopup">Open</button>
</div>
</div>

</div>


<div class="product-popups">




<div class="popup-hide popup" id="popup"> 
<button class="btn btn-primary" id="hidepopup">&times;</button>
<hr>
<div class="row">
<div class="col-sm-4">

<img style="width: 200px;max-width: 90%;" src="1.jpg" alt="">
</div>
<div class="col-sm-8">

price:200DA <br>
<br><br>
</div>
</div>

</div>




<div class="popup-hide popup" id="popup"> 
<button class="btn btn-primary" id="hidepopup">&times;</button>
<hr>
<div class="row">
<div class="col-sm-4">

<img style="width: 200px;max-width: 90%;" src="2.jpg" alt="">
</div>
<div class="col-sm-8">

price:300DA <br>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Deleniti, molestiae totam aliquam 
quas optio praesentium! Soluta id ea est maxime laudantium, iure voluptatibus voluptatum et nemo modi reprehenderit bea
tae. Dolorum?
<br><br>
</div>
</div>

</div>;

</div>
</div>
</p>
</div></answer2>
<exanswer2><div class="answer" i="65027959" l="4.0" c="1606406925" m="1606455788" v="2" a="cy5rdXpuZXRzb3Y=" ai="13573444">
<p>I have completely transformed your JavaScript code without compromising functionality. The updated logic now relies on the `forEach()` method and eliminates the need for function calls within the HTML structure.</p>
<p><div>
<div>
<pre class="lang-js"><code>var popup = document.querySelectorAll('.popup');
var btn = document.querySelectorAll('.card-body button');
var btn_close = document.querySelectorAll('.popup-hide.popup button');

Array.from(btn).forEach(function(btnArray, i) {
btnArray.addEventListener('click', function() {
popup[i].style.display = 'block';
});
});

Array.from(btn_close).forEach(function(btn_closeArray, i) {
btn_closeArray.addEventListener('click', function() {
popup[i].style.display = 'none';
});
});
.cards {overflow: auto;white-space: nowrap;margin-top: 10px;}
.options a {margin-left: 10px;text-decoration: none;}
.card {display: inline-block;margin: 5px; height: 200px ;}
.bgimg {height:410px;}
.scm a {text-decoration: none;}
.fb:hover {color:#4267B2}
.insta:hover {color: #FD1D1D;}
.gm:hover {color: #B23121;}
.centring {margin: auto; display: flex;justify-content: center; align-items: center;}

.popup-hide { position: fixed;
padding: 5px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: 100ms ease-in-out;
border: 1px solid black;
border-radius: 10px;
z-index: 10;
background-color: white;
width: 800px;
max-width: 80%;
display: none;}
.popup-show { position: fixed;
padding: 5px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: 100ms ease-in-out;
border: 1px solid black;
border-radius: 10px;
z-index: 10;
background-color:white;
width: 800px;
max-width: 80%;
display: block;}
<div class="container-full" id="container">
      <div class="product-cards">
        <div class="card" style="width:250px;height: 200px;">
          <img class="card-img-top" src="1.jpg" alt="Card image">
          <div class="card-body">
            <button class="btn btn-primary" id="showpopup">Open</button>
          </div>
        </div>
        <div class="card" style="width:250px;height: 200px;">
          <img class="card-img-top" src="2.jpg" alt="Card image">
          <div class="card-body">
            <button class="btn btn-primary" id="showpopup">Open</button>
          </div>
        </div>
      
      </div>
      
      
      <div class="product-popups">
      
      
      
        <div class="popup-hide popup" id="popup"> 
          <button class="btn btn-primary" id="hidepopup">&times;</button>
          <hr>
          <div class="row">
            <div class="col-sm-4">
             
              <img style="width: 200px;max-width: 90%;" src="1.jpg" alt="">
            </div>
            <div class="col-sm-8">
              
              price:200DA <br>
              <br><br>
            </div>
         </div>
        
        </div>
        
        
        
        <div class="popup-hide popup" id="popup"> 
          <button class="btn btn-primary" id="hidepopup">&times;</button>
          <hr>
          <div class="row">
            <div class="col-sm-4">
             
              <img style="width: 200px;max-width: 90%;" src="2.jpg" alt="">
            </div>
            <div class="col-sm-8">
              
              price:300DA <br>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Deleniti, molestiae totam aliquam 
              quas optio praesentium! Soluta id ea est maxime laudantium, iure voluptatibus voluptatum et nemo modi reprehenderit bea
              tae. Dolorum?
              <br><br>
            </div>
          </div>
        
        </div>
        
        </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

ajax memory leakage

Encountering a gradual memory leak issue in Internet Explorer and Firefox while utilizing a mix of ASP.NET AJAX and jQuery. The situation mirrors the one portrayed on this post: Preventing AJAX memory leaks, but with jQuery and ASP.NET AJAX instead of prot ...

The CSS properties intended for ion-button elements are not taking effect

I'm attempting to set a background color when a ion-button is clicked or maintain the ion-ripple effect after it has filled the button in Ionic 4. I experimented with applying custom CSS states in global.scss, but encountered issues where the active ...

Avoid inadvertently sending an HTTP OPTIONS request when including an authentication token in an Angular HTTP request

Encountering a problem with CORS while attempting to execute a GET request with an Authorization token, but running into issues with OPTIONS. Seeking solutions on how to avoid sending OPTIONS when making a GET request to another server. $http({ ur ...

Is it possible to load all nodes on button click using the XMLHttpRequest Object?

Why is it that when I insert the parent node, nothing shows up -- but when I use the root node ("dataroot"), only the first child node displays in the table even though there are multiple child/sibling nodes? Here's the HTML code: <!DOCTYPE html> ...

Nested divs with independent scrolling capabilities

I am interested in developing a gantt chart that displays days, months, and years at the top with tasks listed below. Here is my progress so far: https://i.stack.imgur.com/tr5y4.png In the image above, the scroll-x functionality works on everything incl ...

The gap between columns in Bootstrap grids

Currently, I am dynamically fetching "boxes" and adding them to the HTML document using ngFor. The number of boxes is unknown in advance. Here is the code I am currently using: <div *ngIf="items && items.length" class="row"&g ...

Locate the position of an element within an array using AngularJS

Consider the following array: $scope.records = [ { "Name" : "Alfreds Futterkiste", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezum ...

Ways to efficiently locate a CSS class amidst numerous stylesheets

Recently, I was assigned a theme for a website that included multiple stylesheets. As I sift through the index.html file, I notice various classes, but struggle to pinpoint which stylesheet they belong to. Instead of manually checking each stylesheet, I ...

Using React Native to showcase a background grid of dimensions {height: 10, width: 10}

Hey there! I'm looking to create a grid that can adapt to different device sizes and screen positions, similar to a chess grid. I want to use this as a background to help with sizing and positioning elements like text and images on the screen. Here&a ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...

"Using a combination of Php, Html5, and xampp for

While attempting to run this PHP file using XAMPP, I encountered an issue. I am working on updating data in a database through a form submission. However, when I input the information and click submit, the page either just reloads or displays a message s ...

Save the processed information in a Kendo Grid column

I am attempting to store data in a specific column by calculating it using information from another column. Currently, I have a function that retrieves the number of available licenses for a given Id in JSON format: function getAvailableLicenses(id) { ...

Unlimited digest loop in Angular.js caused by nested ng-repeat and filter

In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices. angular.module('abc').filter('searchFor', function(){ return ...

The background image of the navigation bar does not adjust properly when resized

Is there a way to make the background image of my navigation bar expand along with the menu when resizing the screen to mobile size and clicking on the hamburger menu? It seems that if my navbar background is a color by default, it expands automatically. ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Using the background-size cover property in Firefox

While working on a website, I encountered an issue where the background image did not display correctly across different browsers. Specifically, when using the background-size: cover property in Chrome and Safari, the image filled up the entire screen as i ...

What is the process for extracting a numerical value from a text box and using it to update a database?

Trying to figure out how to add a numerical value entered into a text box to a value in a database table when the submit button is clicked. Let's say there's a table called customers in the database, with columns for name and balance. The goal i ...

What is the best way to add or modify a timestamp query string parameter?

Looking to timestamp my querystring for browser caching bypass when refreshing page via javascript. Need to consider existing querystring with timestamp and hash tag (http://www.example.com/?ts=123456#example). Tried my own solution but it feels overly co ...

How to Implement Button Disable Feature in jQuery When No Checkboxes Are Selected

I need help troubleshooting an issue with a disabled button when selecting checkboxes. The multicheck functionality works fine, but if I select all items and then deselect one of them, the button disables again. Can someone assist me with this problem? Be ...