Home > Net >  How can I close the last opened popup in order?
How can I close the last opened popup in order?

Time:04-15

How can I close the last opened popup in order?

The image below is an image where popup tags are stacked down whenever a popup is opened.
enter image description here

Below is the applied source.

/* ESC popup close start */
$(document).on('keyup', function(e) {
  if (e.key == "Escape") $('.window .close').last().click();
});
/* ESC popup close end */

CodePudding user response:

  • Be sure that the close click event before the click trigger
  • You need to addClass to the last .window element to avoid it when you order the last item again

$(".close").on("click" , function(){
  $(this).closest(".window").hide();
});


/* ESC popup close start */
$(document).on('keyup', function(e) {
  if (e.key == "Escape") $('.window:not(.hidden)').last().addClass("hidden").find(".close").click();
});
/* ESC popup close end */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >Window 1<div >X</div></div>
<div >Window 2<div >X</div></div>
<div >Window 3<div >X</div></div>

CodePudding user response:

Simply set popup window to any variable and close using that variable using window.close

const daddyWindow = window.open("", "window"   number, "width=200,height=100");
daddyWindow.document.write('window Popup code');
daddyWindow.close();

Try this:

<html>
<header>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        let openedWindows = [];
        let newWindow;
        let number = 0;
        function openWindow() {
            number  ;
            newWindow = window.open("", "window"   number, "width=200,height=100");
            newWindow.document.write(`<a href="javascript:window.close();">Close this window ${number}</a>`);
            openedWindows.push(newWindow);
        }

        $(document).on('keyup', function (e) {
            if (e.key == "Escape") {
                if (openedWindows && openedWindows.length >= 0 && openedWindows[openedWindows.length - 1]) {
                    openedWindows[openedWindows.length - 1].close();
                    openedWindows.pop()
                }
            }
        });
    </script>
</header>

<body>
    <h3 style="color:brown"> Close Window Example </h3>
    <button onclick="openWindow()">Open New Window</button>
</body>

</html>
  • Related