Popup windows are struggling to close correctly

Having an issue with multiple popups not closing properly when clicking another link. The popups keep stacking up even though the close function has been specified in the code.

$(document).ready(function() {//$('a.poplight[href^=#]').click(function(){
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"></a>');
var popMargTop = ($('#' + popID).height() + 10) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
$('body').append('<div id="fade"></div>');
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'})
return false;
});
$('a.close, #fade').live('click', function() {
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
});
return false;
});
});

CSS:

.popup_block{
    display:none;
    background:#151515;
    padding:20px;
    float:left;
    position:fixed;
    top:40%;left:50%;
    z-index: 99999;
    line-height:20px;

}

*html #fade {position: absolute;}
*html .popup_block {position: absolute;}
#fade {
    display:none;
    position:fixed;
    left:30%;
    top:0px;
    width:70%;
    height:100%;
    z-index:9999;
    background:#000; /* change to #fff for solid white */
    opacity:1; /* change to opacity:1; */
}

HTML:

<div id="box1" class="popup_block">
HEY
</div>
 <div id="box2" class="popup_block">
    YO
 </DIV>
  <div id="box3" class="popup_block">
 hello
 </div>
</div></div></div></div></div></div></div></div></div></div>

Answer №1

Upon reviewing the code you shared, I noticed a few areas that could be improved. It seems like you might have copied only a portion of the complete code, as the repeated

</div></div></div></div>
structure stood out immediately. To better understand the functionality, I inserted your code into a JsFiddle and made some enhancements to it. One key point is the use of numerous IDs prefixed with #, which I generally recommend avoiding unless absolutely necessary. The issue with the close function not functioning properly could be due to conflicting IDs for multiple #fade elements. By replacing IDs with classes, the revised code now operates smoothly.

$("document").ready(function() {
    $("a").click(function () {
        var popID = $(this).attr("class"); 
        var tarDiv = $("div." + popID);
        var popMargTop = (tarDiv.height() + 10) / 2;
        var popMargLeft = (tarDiv.width() + 80) / 2; 
        tarDiv.fadeIn()
            .css({
                "width": 300,
                "margin-top": -popMargTop,
                "margin-left": -popMargLeft
            });
        var closeA = $("<a href=\"#\" class=\"close\">X</a>");
        closeA.appendTo(tarDiv)
            .click(closeMe);
        var fadeDiv = $("<div class=\"fade\" style=\"filter:alpha(opacity=80);\" />");
        fadeDiv.appendTo($("body"))
            .fadeIn()
            .click(closeMe);
        function closeMe() {
            $(".fade , .popup_block").fadeOut(function() {
                $(".fade, a.close").remove();
            });
        }
    });
});

http://jsfiddle.net/jessikwa/kprwnzcc/

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

Implementing Update and Delete Features for Database Rows in Repeater

I have a repeater set up to extract and display data from a SQL Server database. Each row in the database has corresponding buttons added to it. Below is the code used to populate the repeater: SqlConnection connR; string connectionStringR = Configu ...

Updating with Ajax is functional for radios and checkboxes, however it does not work for buttons

When a button is clicked, I want the form to process and update accordingly. HTML: <input type="button" value="5.00" name="updatefield" id="updatefield" class="chooseit"> I have also tried: <button name="updatefield" id="updatefield" class="ch ...

Is it possible for JavaScript to be cached when it is located within the body tag of an HTML document?

Currently, I am exploring the topic of How to optimize HTML rendering speed, and came across the idea that scripts in the HEAD tag can be cached. I'm curious, is it possible to cache JavaScript in the BODY tag? If not, I wonder why YUI suggests placi ...

Determine the quantity of classes based on the part name

I have the code snippet provided below: <ul id="towns"> <li class="clearfix odd 516_499_132_0_0 town132">...</li> </ul> I am looking to extract the specific class "town132" as a parameter, but the number - such as 132 in this ...

List of elements inside an HTML box

In my current HTML project, I am trying to include a box on a webpage that contains a scrollable list of elements. I want the content inside the box to scroll independently without affecting the rest of the page. Is there a way to achieve this? ...

What is the best way to make a table fill 100% of the available height

Is this a Repetitive Question? How to stretch an HTML table to 100% of the browser window height? Just like the title says, I am looking for a way to make my table element stretch to 100% height even when the content does not entirely fill the page&ap ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

The sidebar is refusing to stick. I've exhausted all resources on Stack Overflow trying to fix it

Having issues with the sticky sidebar on my website, I've tried solutions from various Stack Overflow threads: Understanding "position: sticky;" property Fix for position:sticky not working Implementing sticky sidebar when scrolling down/up The is ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Leveraging Greasemonkey along with jQuery to capture and manipulate JSON/AJAX data on a webpage

In my previous inquiry on Stack Overflow, I received some insight into my issue regarding Greasemonkey interpreting jQuery. However, the challenge remains in directing GM to retrieve data from a specific location and place it into an array. When visiting ...

What does the single-threaded nature of JavaScript signify in terms of its intricacies and ramifications?

As someone relatively new to Javascript and JQuery, I recently discovered that Javascript operates on a single-threaded model. This has left me wondering about the implications it carries: What should be taken into account when writing JavaScript code? Ar ...

Initialization of directive failed to occur properly

Utilizing the angular-ui-bootstrap tabs directive, I tried to create tabs. However, upon logging each controller and link function, the initialization order appears incorrect. Expected Order outer - controller Inner - Controller Inner - Link Inner - C ...

When rendering in React, retrieving the value from sessionStorage always yields a single result

I have encountered an issue with storing the jwt key in localStorage when a user logs in. I am trying to make the app render either "Login/Register" or Logout buttons/links based on whether the key exists. However, the function I created seems to always re ...

Having issues with your PHP dropdown database code?

I am having trouble with the code below. It seems to display the HTML portion correctly, but it is not fetching the data from my database. My goal is to populate a drop-down list with data from the database and then display it in a table below when the u ...

Secure authentication with Keycloak API

In my HTML page with JavaScript, I am trying to implement auto-login functionality for the user. Below is the code I have written: var url = "http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token"; const response = await fetch(url, { ...

Show the initially chosen option in a dropdown menu when updating a record using mysqli

I recently came across a PHP page that handles relocation requests and allows users to edit them as needed. While the add page features dropdown boxes, the edit page simply displays them as text fields. This makes it difficult for users to select a differ ...

Tips for ensuring form elements do not contain white space before submitting through AJAX

Before sending my form using AJAX request, I want to validate the form elements. Even though it checks for errors, the form still gets submitted. This is my code: $('#accountFormAddEdit').on('submit', function(e){ e.preventDef ...

What steps can be taken to make the carousel inconsistent when relying on the assigned id in props?

I recently developed a slider with slots, but encountered an issue. The code for this component revolves around the use of IDs for each slide as prop, making it unnecessarily complex. I am convinced that there is a more straightforward way to achieve the s ...

Discover the child of the delegated event div using jQuery

Can you assist me in resolving this issue? My HTML structure appears as follows: <div id="main-randompart"> <!--Inserted into the DOM during runtime--> <div class="close"> X </div> <img src="somesrc..."> ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...