Is there a way to ensure only one popup opens at a time rather than having two popups appear simultaneously?

I am facing an issue with multiple popups where clicking on a number opens all the popups instead of just the one belonging to that number. Can anyone provide some assistance?

jQuery(document).ready(function($){
//Function to open popup
$('.cd-popup-trigger').on('click', function(event){
event.preventDefault();
$('.cd-popup').addClass('is-visible');
});
  

//Function to close popup
$('.cd-popup').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('.cd-popup') ) {
event.preventDefault();
$(this).removeClass('is-visible');
}
});
//Close popup when pressing the escape key
$(document).keyup(function(event){
    if(event.which=='27'){
    $('.cd-popup').removeClass('is-visible');
    }
    });
});
/* CSS Reset */

External fiddle

Answer №1

In order to apply a class to a specific div, you should target the .cd-popup class that follows it rather than all instances of the .cd-popup class.

Modify the line like so

$(this).next('.cd-popup').addClass('is-visible');

jQuery(document).ready(function($){
//open popup
$('.cd-popup-trigger').on('click', function(event){
event.preventDefault();
$(this).next('.cd-popup').addClass('is-visible');
});
  

//close popup
$('.cd-popup').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('.cd-popup') ) {
event.preventDefault();
$(this).next('.cd-popup').addClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
$(document).keyup(function(event){
    if(event.which=='27'){
    $('.cd-popup').removeClass('is-visible');
    }
    });
});
/* CSS Reset */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}

/* Primary styles */
html * {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

*, *:after, *:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  font-size: 100%;
  font-family: "Lato", sans-serif;
  color: #8f9cb5;
  background-color: #ffd88f;
}

a {
  color: #35a785;
  text-decoration: none;
}

/* Modules - reusable parts of our design */

...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#0" class="cd-popup-trigger">1</a>
<div class="cd-popup" role="alert">
...

<a href="#0" class="cd-popup-trigger">2</a>
<div class="cd-popup" role="alert">
...

Answer №2

Fiddler

$('.cd-popup-trigger').click(function(){
$('.cd-popup-trigger').siblings('.cd-popup').removeClass('is-visible');
var close = $(this).next().find('.cd-popup-close');
var curtrigger = $(this).next();

$(curtrigger).addClass('is-visible').siblings(curtrigger).removeClass('is-visible')
$(close).click(function(){
$(this).parents('.cd-popup').removeClass('is-visible')

})
});
/* Unique reset 
   CSS styles for our design
*/

html,
body {
  background-color: #FFFFFF;
} 

div,
span {
  display: block;
}

a {
  text-decoration: underline;
}

table {
  border-collapse: separate;
}


/* -------------------------------- 

Custom styles

-------------------------------- */

html * {
  font-weight: bold;
}

img-replace {
  /* replace text with an image */
  display: inline-block;
  overflow: visible;
  color: black;
  white-space: normal;
}


/* -------------------------------- 

Unique info 

-------------------------------- */

.cd-nugget-info {
  text-align: left;
  position: fixed;
  width: 50%;
  height: 30px;
  line-height: 30px;
  bottom: 20px;
  left: 20px;
}

.cd-nugget-info a {
  position: relative;
  font-size: 12px;
  color: #000000;
}

.no-touch .cd-nugget-info a:hover {
  opacity: 1;
}

.cd-nugget-info span {
  vertical-align: top;
  display: block;
}

.cd-nugget-info span svg {
  display: inline;
}

.cd-nugget-info .cd-nugget-info-arrow {
  fill: black;
}


/* -------------------------------- 

Main components 

-------------------------------- */

header {
  height: 150px;
  line-height: 150px;
  text-align: center;
  background-color: #CCCCCC;
  color: #000000;
}

header h1 {
  font-size: 18px;
}

.cd-popup-trigger {
  display: inline-block;
  width: 40px;
  height: 40px;
  margin: 2em auto;
  text-align: center;
  color: #FFF;
  font-size: 11px;
  font-weight: bold;
  border-radius: 50em;
  background: #AAAAAA;
}

.cd-popup-trigger:hover {
  opacity: 0.8;
}

@media only screen and (min-width: 1024px) {
  .cd-popup-trigger {
    margin: 4em auto;
  }
}


/* -------------------------------- 

Popup 

-------------------------------- */

.cd-popup {
  position: absolute;
  left: 10%;
  top: 10%;
  height: 90%;
  width: 90%;
  visibility: hidden;
}

.cd-popup.is-visible {
  visibility: visible;
}

.cd-popup-container {
  position: static;
  width: 80%;
  margin: 5em auto;
  background: #DDDDDD;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
}

.cd-popup-container p {
  padding: 2em 1em;
}

.cd-popup-container .cd-buttons:after {
  content: "";
  display: table;
  clear: both;
}

.cd-popup-container .cd-buttons li {
  float: right;
}

.cd-popup-container .cd-buttons a {
  display: inline-block;
  height: 40px;
  line-height: 40px;
}

.cd-popup-container .cd-buttons li:first-child a {
  background: #BBBBBB;
}

.no-touch .cd-popup-container .cd-buttons li:first-child a:hover {
  background-color: #CCCCCC;
}

.cd-popup-close {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 25px;
}

.cd-popup-close::before,
.cd-popup-close::after {
  content: '';
  position: static;
  top: 9px;
  width: 15px;
  height: 2px;
}

.cd-popup-close::before {
  transform: rotate(45deg);
  left: 5px;
}

.cd-popup-close::after {
  transform: rotate(-45deg);
  right: 5px;
}

.is-visible .cd-popup-container {
  transform: translateY(10px);
}

@media only screen and (min-width: 1024px) {
  .cd-popup-container {
    margin: 6em auto;
  }
}
<a href="#0" class="cd-popup-trigger">1</a>
<div class="cd-popup" role="alert">
  <div class="cd-popup-container">
  <h2>
  Custom Popup One
  </h2>
    <p>This is a unique popup message.</p>
    <ul class="cd-buttons">
      <li><a href="https://www.unique-link.com">Source</a></li>
    </ul>
    <a href="#0" class="cd-popup-close img-replace">Close</a>
  </div>
  <!-- cd-popup-container -->
</div>
<!-- cd-popup -->

<a href="#0" class="cd-popup-trigger">2</a>
<div class="cd-popup" role="alert">

  <div class="cd-popup-container">
  <h2>
  Custom Popup Two
  </h2>
    <p>This is another unique popup message.</p>
    <ul class="cd-buttons">
      <li><a href="https://www.another-link.com">Source</a></li>
    </ul>
    <a href="#0" class="cd-popup-close img-replace">Close</a>
  </div>
  <!-- cd-popup-container -->
</div>
<!-- cd-popup -->

Answer №3

Looking for a quick fix? Try opening the pop-up right after clicking on the <a>. However, keep in mind that this solution may not be ideal as it relies on the specific placement of the pop-up in the HTML structure.

https://jsfiddle.net/b5v1vpd1/3/

For a more robust solution, consider assigning each <a> element with data-attributes to specify which pop-up should open. This approach offers greater flexibility as the JavaScript code does not rely on a fixed HTML structure; you can place the pop-up anywhere on the page and it will still function correctly.

jQuery(document).ready(function($){
//open popup
$('.cd-popup-trigger').on('click', function(event){
event.preventDefault();
var popup_key = $(this).attr('data-target');
    var $popup = $('*[data-popup-nr='+popup_key+']');
$popup.addClass('is-visible');
});
  

//close popup
$('.cd-popup').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('.cd-popup') ) {
event.preventDefault();
$(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
$(document).keyup(function(event){
    if(event.which=='27'){
    $('.cd-popup').removeClass('is-visible');
    }
    });
});
[CSS Code Snippet]
[Script Tag Contains CDN Link and HTML Markup for Pop-Ups]

Please note: Your code may have minor CSS issues (such as button overlapping the pop-up), which you can address separately.

Answer №4

Here is the code snippet you can use:

// trigger popup
$('.trigger-popup').on('click', function(event){
   event.preventDefault();
    $(this).next('.popup-container').addClass('is-visible');
});

Ensure that your first modal window is placed under the second hyperlink.

Answer №5

To resolve your issue, it's important to have a good grasp of jQuery. Upon reviewing your code, the problem lies within the JS section:

$('.cd-popup-trigger').on('click', function(event){
    event.preventDefault();
    $('.cd-popup').addClass('is-visible');
});

1) The click event is bound to both cd-popup-trigger elements, causing the same function to run for both.

2) By using event.preventDefault(), you are preventing the default click behavior unnecessarily. Following that,

$("popup1").addClass("is-visible")
will add the class 'is-visible' to all elements with the 'cd-popup' class, displaying them all.

A simple fix would be to assign unique IDs to each trigger and cd-popup element:

<a href="#0" class="cd-popup-trigger" id="trigger-popup1">1</a>
<div class="cd-popup" role="alert" id="popup1">...</div>
...
<a href="#0" class="cd-popup-trigger" id="trigger-popup2">1</a>
<div class="cd-popup" role="alert" id="popup2">...</div>

Then, within the click event, you can identify the clicked ID:

$('.cd-popup-trigger').on('click', function(event){
    event.preventDefault(); // not necessary
    var triggerid = $(this).attr('id'); // get the ID of the clicked element
    switch(triggerid){
        case 'trigger-popup1':
             $("#popup1").addClass("is-visible");
             break;
        case 'trigger-popup2':
             $("#popup2").addClass("is-visible");
             break;
    }
});

While not the optimal solution, this approach aids in understanding how jQuery operates.

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

Center the first column in jQuery Datatables

Looking to center-align only the first column named "Status": $("#TransactionTable").DataTable({ ajax: { url: '/Transaction/SearchMockup', type: 'POST', data: { ...

What is causing my JS/JQuery code to only function in the console of a web browser?

I am having trouble with the $(element).scroll(function(){}); function. When I put it into a js file, it does not work properly, but when I enter it directly into the console (just the scroll func), it works fine. My goal is to implement scrolling paginat ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

Conceal Class When Input Value is "X"

Is there a way to dynamically hide a specific seller (<div class="seller">) from a table using CSS and PHP based on a get parameter? Each seller has a unique ID represented by <input type="hidden" value="1" name="seller_id">. For example, if I ...

Question about the 'form-floating' class inconsistency in Bootstrap version 5.2

Currently utilizing Bootstrap 5.2, I have integrated a form with the following snippet: <div class="row mb-2 align-items-center"> <div class="col-sm-4"> <label class=&qu ...

Issue with form action redirection on Node JS Express server not functioning correctly

My EJS application involves using jQuery in the JavaScript code to fetch JSON data from the Google Custom Search API. The app then uses the GET method to navigate to /search, passing the query as the attribute for q. Here's an example of the form&apos ...

Learn how to transform the html:options collection into html:optionsCollection

What is the best method to transform this code snippet: <html:options collection='catList' property='catId' labelProperty='catName'> using the <html:optionsCollection> tag? ...

Search for and swap out every item in a multi-tiered array

I am working with an array where the first column represents an id: var mainarray = [ ["1001","P6","P8"], ["1002","P7"], ["1003","P7","P8","P10"], ["1004","P6","P10"], ]; My goal is to replace each 'P' element with its corresponding animal from ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

Creating a Density Chart Using SVG

I am currently working on converting this chart into SVG Format. I have made some progress, but I still need to ensure that both sides match perfectly when it goes up and down. https://i.sstatic.net/jpkoo.png <div class='chart'> <s ...

Alignment of a div at the bottom inside a jumbotron using Bootstrap 4

Searching for answers on how to vertically align a div within a jumbotron, I have come across plenty of solutions for middle alignment but none for bottom alignment. <section id="profileHero"> <div class="container"> <d ...

The UTF-8 data sent by JQuery AJAX is not being correctly processed by my server, but only in Internet Explorer

When I send UTF-8 Japanese text to my server, it works fine in Firefox. Here are the details from my access.log and headers: /ajax/?q=%E6%BC%A2%E5%AD%97 Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Content-Type application/x-www-form-urlencoded; char ...

Content located on the right-hand side of the menu

I am currently working on a vertical navigation menu design, but I am facing some issues with aligning the text to start from the very left edge of the element. HTML <div class="jobs-links"> <ul> <li><a href="renovations. ...

Methods for opening HTML documents in webView2 by selecting links in webView1

I have implemented a custom navigation bar using webView1 and a local html file that contains some links. My goal is to load the requested html file into webView2 when one of these links is clicked. Is this achievable? @Override public void onCreate(Bun ...

The Challenge of Referencing Javascript Files (including jQuery)

Previously, I had the following code snippet: <head> <script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type="text/javascript"> var optPrompt = "- Select One -"; var subCats ...

Excessive-y does not have scrolling capabilities

I'm having an issue with the overflow-y: scroll property under the "Online Contacts" section in my code. It's not working as expected, but when I change the position to absolute and make certain adjustments, it starts working. I'm using Boot ...

Encountering the issue of 'Uncaught SyntaxError: Unexpected token <'

I keep encountering this error repeatedly. I followed the example at https://facebook.github.io/react/docs/thinking-in-react.html#step-5-add-inverse-data-flow and it works perfectly on jsfiddle. However, when I try to implement the same code in mvc's ...

Steps to export data to Excel in ASP.NET MVC 5 without needing to refresh the page

I am experiencing an issue with exporting data into Excel. Every time I try to press the Export Data to Excel button, the page reloads. Is there a way to prevent this from happening without reloading the entire page? Your assistance would be greatly apprec ...

At what point do browsers automatically insert CSS styles as attributes without them being explicitly defined?

Greetings Code Gurus, I find myself grappling with an unexpected CSS anomaly while developing a website. Here is the puzzling code snippet: <div id="..." style="padding-bottom: 78px; padding-top: 78px;" >...</div> These styles are manifesti ...

ReactJS input field icons are being obscured by text

insert image description hereI've developed a multi-dropdown component. The icons are being blocked by the text in the input field, as illustrated below. My goal is to make the text wrap around the icons smoothly. ...