This is my js code first i have tried if someone made changes in fields then this modal shows if i tried to go other pages without saving. That’s work fine for me. But on browser back button a problem shows it didn’t show the modal and goes back. So i have use this onbeforeunload so it can work now it’s work but didn’t gave me time to click on modal buttons that i made for them to stay on the page leave to that new page on the click of stay button it should stay on that page and on click of delete button it should go to that clicked page but modal didn’t show for a second when i click on browser back button it goes back immediately
var modal = $(".leave_modal"); var modalContent = modal.find(".modal-content"); var deleteBtn = modal.find(".close"); var stayBtn = modal.find(".btn-stay"); var saveBtn = $("#saveBtn"); var clickedLinkURL; // Set initial styles for modal content modalContent.css({ transition: "transform 0.3s ease, opacity 0.3s ease", transform: "scale(0.8)", opacity: 0 }); function openModal() { modal.css("display", "block"); setTimeout(function() { modalContent.css({ transform: "scale(1)", opacity: 1 }); }, 50); } function closeModal() { modalContent.css({ transform: "scale(0.8)", opacity: 0 }); setTimeout(function() { modal.css("display", "none"); }, 300); } deleteBtn.on("click", function() { closeModal(); $("body").off("click", "a", preventLinkClick); if (clickedLinkURL) { window.location.href = clickedLinkURL; // Redirect to the URL of the clicked link } }); stayBtn.on("click", closeModal); $(window).on("click", function(event) { if (event.target === modal[0]) { closeModal(); } }); function preventLinkClick(event) { var target = $(event.target); if (target.is("a") && target.attr("href") && target.attr("href") !== "#") { if ($("#changesMade").val() === "true") { event.preventDefault(); // Prevent default only if changes have been made clickedLinkURL = target.attr("href"); // Store the URL of the clicked link openModal(); } else { } } } $("body").on("click", "a", preventLinkClick); // Function to set changesMade to true when changes are detected $("input, select, textarea").on("input change", function() { $("#changesMade").val("true"); }); window.onbeforeunload = function(event) { if (changesMade) { openModal(); return null; } }; function showConfirmationModal(url) { }