Learn how to successfully carry on with event.preventdefault in JavaScript

Is there a way to create a modal that prompts the user to confirm if they want to leave the page without committing changes?

These changes are not made within a <form> element, but rather on a specific object.

I've attempted to use both $routeChangeStart and $routeChangeSuccess to detect when the user is trying to leave the page:

$scope.$on('$routeChangeStart', function(event, current) {
  event.preventDefault();
  ConfirmationModal.fire("Are you sure?", response => {
    if (response) {
      // How can I continue with the default action here??
    }
  });
}

The code above successfully stops the user from leaving the page. However, after confirming the modal, I'm unable to proceed with the page navigation. I can prevent the default action but not continue it.

I have also tried using:

$location.path(PATH) but this approach did not work either.

Furthermore, even if the user tries to leave the page again, the event.preventdefault still remains in effect.

Answer №1

To ensure user confirmation before changing routes, you can implement a flag and a conditional statement:

Consider implementing the following code snippet:

$scope.confirmationRequired = true;

$scope.$on('$routeChangeStart', function(event, current) {
  // Prevent route change if confirmationRequired is set to true
  if ($scope.confirmationRequired) {
    event.preventDefault();
    CustomModal.show("Are you sure?", response => {
      if (response) {
        $scope.confirmationRequired = false;
        $location.path('/new-path'); // Include the correct path here
      }
    });
  }

})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing me to not receive a 404 error when dealing with an unhandled state?

Currently, I am utilizing $stateProvider to configure my states in the following manner: constructor($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider. state("something", { url: "/index.html" }) ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

Select the small image to reveal the larger overlay image

I have a grid of images and I want each image to expand into fullscreen when clicked. However, the JavaScript I am using is causing only the last image in the grid to overlay. How can I resolve this issue? Here is the code I am currently using: http://js ...

JavaScript, PHP handlers, and CommentBox all work together seamlessly to create

$("#login").click(function(){ $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){ console.log(data); //retrieves data from login box and sends it to the handler, returning a JSON array }); template = $("#hid ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

What steps should I take in Three.js to make the "terrain" look three-dimensional?

Currently, I am in the process of developing a 3D terrain using Three.js along with ImprovedNoise.js. Utilizing the examples provided on the Three.js website, I have successfully created what appears to be terrain. However, my issue lies in the fact that i ...

Disabling cache in AngularJS is being overridden by Chrome's cache

I'm currently encountering an interesting caching issue while using Chrome. My angularjs service looks like this: var url = '/api/acts/' + accountId + '/policy/?filter=NEW_POLICY'; return $http({ ...

The function Sequelize.create() does not exist

My attempts to push my DB with sequelize are not working, even though I have set up this schema for the DB: module.exports = (sequelize, DataTypes) => { const Problems = sequelize.define("Posts", { theme: { type: DataTypes.ST ...

Guide on invoking a node.js function from an express-rendered ejs page

My express server currently has a button that triggers a POST request to activate a function in my node.js server. Instead of using a traditional POST request, I am interested in implementing something like AJAX so that the page doesn't reload. Is th ...

How can I ensure that VueJS only starts loading data after the initial API call has been completed?

After retrieving data from an API, I populate a form in my component. The challenge I am facing is that the watchers are triggered immediately after populating the initial data. I want them to be triggered asynchronously. Additionally, I need to prevent th ...

Intellisense missing in VSCode for Angular and typings

Attempting to start a new project using Angular 1.5.5 and looking to incorporate TypeScript into my coding process within Visual Studio Code. I have included the necessary typings for Angular in my project: typings install angular --save --ambient I&ap ...

Is it necessary to uncheck the row checkbox when inputs are left empty after blurred?

Two issues have cropped up here. When clicking on an input within a row, the corresponding checkbox should be checked. Currently, only the first text input is able to check the checkbox due to the use of .prev(). Is there a different approach that can be t ...

Passing events from Swift or Objective-C to JavaScript is a seamless process

A custom class was created with the following condensed version provided. For a reference to the full file, please visit this link. @objc(NativeMethods) class NativeMethods: RCTEventEmitter { @objc(sendEventToJSFromJS) func sendEventToJSFromJS { s ...

The Art of jQuery Data Processing

I'm currently working on extracting data from a form submission. Below is the code I've been using. function handleSubmission() { $("#questionForm").submit(function() { $.post("SubmitQuestion.php", $("#questionForm").serialize()).done(functi ...

Reorder data in an array using a specific field in AngularJS

I am working with an array that looks like this: [Object,Object,Object]; Each object in the array has a property named "rate". I need to sort these objects based on their rate property. In my JavaScript, I have a variable called $scope.restaurants.data, ...

Exploring the dynamic duo of Django and DataTables: a guide on incorporating

Have you cautiously attempted to fetch data using AJAX, and displaying it in a datatable works seamlessly, but the issue arises when attempting to search or sort within the table. It seems that upon doing so, the data is lost, necessitating a page reload. ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

How does BullMQ stand out from other message queue implementations?

Recently, I've been exploring the documentation for BullMQ: https://github.com/taskforcesh/bullmq One thing that caught my eye in its comparison chart was the absence of projects like RabbitMQ or NATS Streaming. It seems that BullMQ is focused on ha ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...