Using scroll disable in conjunction with "Esc" key

I have scroll disable on a site that works when a modal form is open. Clicking the page CTA opens the modal (disables scroll), and clicking the “X” (enables scroll) and closes the modal.

However, I want to also enable hitting the ESC key close the modal. Only problem is, since the “X” isn’t being clicked, scroll isn’t re-enabled. I’m not great with custom code, but have used chatgpt to successfully implement the esc close function.

<script>
document.addEventListener('keydown', function(event) {
  if (event.key === "Escape") {
    // Check if the modal is currently open
    if ($('.modal-class').is(':visible')) {
      // Close the modal
      $('.modal-class').hide();
    }
  }
});
</script>

Is it possible to somehow integrate these to work together? Thank you!!

Live page
Read only

hey @Drcontempo! I am so sorry I missed your message. you can simulate a click on the X to enable the scroll by adding one line of code to the snipper your shared above.

<script>
document.addEventListener('keydown', function(event) {
  if (event.key === "Escape") {
    // Check if the modal is currently open
    if ($('.modal-class').is(':visible')) {
      // Close the modal
      $( '.x-class ).click (); // Replace the ".x-class" with your elements class
      $('.modal-class').hide();
    }
  }
});
</script>

You could also remove the $('.modal-class').hide() and just let the click on the X do this for you

1 Like

Ok cool thank you! I’ll try it out