Alert on closing modal which asks user to confirm they want to close form

I would like to display a confirmation alert to users when they close a modal form, if they click OK I’d like the modal to close, if they click cancel the modal will stay open.

I’ve got as far as getting the alert to display, can anyone help with preventing the modal from closing if the user clicks cancel. This is what I have so far;

    $('.kn-modal-bg').off('click'); // prevent modal forms being closed from bckgrd click
    $('.close-modal').click(function() { //add alert when closing modal
      if (confirm('Any un-submitted work will not be saved, do you wish to continue?')) {
        // close alert and modal
      } else {
        // don't close modal

Any help greatly appreciated,

Hi Amanda,

If you always want to remind the user yourself, you can use the same .off() method you’ve used for preventing the modal from being closed via the background click:


Then, in your click function, you can either reload the page yourself or hide the modal background (which will effectively hide the modal).

// redirect to the previous page
let currentURL = window.location.href;
let penultimateIndex = currentURL.lastIndexOf('/', currentURL.lastIndexOf('/') - 1);
let newURL = currentURL.substring(0, penultimateIndex);

// OR
// hide the modal

Hope that helps!

Hi JD,

That’s great thanks for taking the time to reply. I’d played around with hiding the modal, but had the issue with the URL still being that of the modal form, using your code I think I can get it working as I’d like.

I will post back my results when I have something working