Escape Key Working Only on the first CMS Modal But Not The Others

I’m using this code to close the modals with ESC key. But it’s only working for hte first cms item modal.

How can I make it work for any card I click on?

Thanks!

Best guess is that querySelector to find the close button is searching the document ( thus finding the first one ) rather than the child elements of your modal.

Generally you’d locate the modal, then find the close button within it, then click it.

Hey Michael! Thanks for the help! Unfortunately, I’m not quite good at code, would you have a better code solution?

I don’t generally write code in forum responses. Aside from the time involved, it’s important for you to understand the solution so that you can adjust it - otherwise your site will break when you adjust your site design.

I’d start here. Since you’re capturing the key at the document level, you want to close all of the dialogs, not just the first one.

GPT is useful to help you learn basic coding as well.

Thanks for giving the advice about chatGPT! I explained my problem and it gave me the exact code I need which works! This is what it gave me (for those watching):

"It seems like you’re targeting the modal using a class selector, which would indeed only affect the latest modal because it’s selecting the first one it finds. To ensure that the script works with any modal, you need a way to target the specific modal that is currently open.

One way to achieve this is by adding an identifier to each modal when it opens, and then using that identifier to target the correct modal to close. Here’s how you could modify your script:

html

Copy code

<script>
document.addEventListener("keydown", function (event) {
  // Check if the pressed key is ESC (Escape key)
  if (event.key === "Escape") {
    // Check if any modal is visible
    var modals = document.querySelectorAll(".cards-modal");
    modals.forEach(function(modal) {
      if (getComputedStyle(modal).display !== "none") {
        // Simulate a click on the close button of this modal
        var closeButton = modal.querySelector(".cards-modal-bg");
        if (closeButton) {
          closeButton.click();
        }
      }
    });
  }
});
</script>

With this modification, the script will iterate over all the modals that are currently open and close each one individually if the Escape key is pressed. This should ensure that it works with any modal that is currently open, regardless of which card triggered it."

We ran across this issue as well in a project for a client and created a solution for it!

This tutorial talks about the issue, and how our code fixes it as well as walking you through setting it up.

If you have any questions feel free to tag me!
Happy Wednesday!