Let's unravel this JavaScript enigma: the code snippet window.confirm = divConfirm(strMessage) awaits

Imagine a scenario where you have an old website with a lot of existing JS code. If a user wants to update all the alert messages to modern, stylish Div-based alerts commonly used in jQuery, YUI, Prototype, etc., there are primarily three types of JS dialogs to consider:

1. alert

To change this, it's simple: just create a new function that displays the div popup and message, then override the window.alert function.


function showDivAlert(strMessage){ <br/>
//div popup logic and code <br/>
} <br/>
 <br/>
window.alert = showDivAlert; <br/>

2. prompt

This one is also straightforward - write a function that accepts a string and displays a text box for input value. Since the return action is based on clicking the "OK" button, the process is easy.


function showDivPrompt(strMessage){ <br/>
//div pop up to show the text box and accept input from the user <br/>
} <br/>
window.prompt = showDivPrompt; <br/>

3. confirm

Unlike the first two, overriding and modifying the default confirm dialog has its complications. The default JS confirm dialog halts JS execution until the user clicks OK or Cancel, which determines the return value (true/false). However, using a div popup does not stop the execution flow, posing a problem. Implementation of the confirm dialog is possible by binding methods for both OK and CANCEL actions to their respective buttons. This results in a function signature like:

function customConfirm(msg, OkAction(), CancelAction)

Unfortunately, this solution does not facilitate a site-wide change of the confirm dialog as easily as with the alert dialog. Question
While I'm unsure if achieving this is possible, it seems feasible using certain JS patterns. Please let me know if such an approach is viable.

Answer №1

It seems that changing the confirm dialog across the site is a problem without an easy solution like we did with alert();

That's right. Replicating the synchronous behavior of alert/confirm/prompt functions in native JavaScript is not feasible. Although there is a non-standard method called showModalDialog that can achieve this using a separate pop-up document, it's not well-supported by all browsers and is generally discouraged.

Therefore, the plugin-replacement approach will not work here. You'll need to manually update every instance where these methods are used in your script.

The common practice is to use inline anonymous functions to maintain local variables through closures. For example, you can replace:

function buttonclick() {
    var id = this.id;
    if (confirm('Are you sure you want to frob ' + id + '?'))
        frob(id);
    wipe(id);
}

with:

function buttonclick() {
    var id = this.id;
    myConfirm('Are you sure you want to frob ' + id + '?', function(confirmed) {
        if (confirmed)
            frob(id);
        wipe(id);
    });
}

If you require preservation of the this keyword, you may need to use nested closures or function.bind. Handling calls to confirm within a loop adds complexity to the situation.

Additionally, it's crucial to ensure that critical global state remains unchanged while the confirm box is active. One way to mitigate this risk is by overlaying a page element to prevent user interactions during the confirmation process. However, timeouts can still pose challenges in this scenario.

Answer №2

Each of the 3 methods mentioned above actually halts javascript execution, not just the confirm dialog, because they all create modal dialogs. Personally, I prefer to keep things as asynchronous as possible since modal dialogs block interaction with the current document.

Your best option would be to utilize callback functions from the new confirm popup, as you had suggested.

I'm a bit unclear on what your exact goal is here. It seems like you want to:

  • Execute some javascript code
  • Show a "confirm" box
  • Pause until the user clicks either the ok or cancel button
  • Resume code execution upon clicking ok, and return if the user clicks cancel.

The reason for doing this is that replacing the function with callbacks would necessitate rewriting every section of code that uses the confirm function. In my opinion, it would be better to restructure the code so it runs asynchronously. There's no way to delay script execution without freezing up the document, which includes the actions of your dialog prompts.

Answer №3

By switching the roles of Alert / Prompt / Confirm, you can introduce delays in code execution to accommodate user interactions.

Once these functions are overridden, the code can seamlessly continue its operation.

To implement this, adjustments need to be made throughout the code to emulate asynchronous behavior.

After making these changes, various plugins like sexy-alert-box can be utilized to replace standard Alert / Prompt / Confirm functionalities.

Answer №4

To create a confirm function, the signature would look like this:

 function customConfirm(message, onOK, onCancel);

Usage example:

 function customConfirm(message, onOK, onCancel){
   var userResponse = promptUserForConfirmation();
   if (userReponse) {
     onOK();
   } else {
     onCancel();
   }
 }

In order to pass functions as arguments to another function, simply provide the function name without parentheses. The function structure remains the same.

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

Referencing a JSON object

Here is a JSON list of search terms: [ "halo", [ "halo reach", "halo anniversary", "halo 4", "halo 3", "halo mega bloks", "halo 2", "halo sleepsack", "halo wars", "halo reach xbox 360", "halo combat evolved" ], ...

Tips for submitting JSON data to the specified input area with AngularJS

I have a json object that looks like this: var jsondata = { "id": 1, "name": "Test Name", "price": 100, "city": "XYZ" }; I am trying to post/send this data to a specific url location when the Send button is clicked. The url location can be entered in an ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

React HTML ignore line break variable is a feature that allows developers to

Can you help me with adding a line break between two variables that will be displayed properly in my HTML output? I'm trying to create an object with a single description attribute using two text variables, and I need them to be separated by a line b ...

Error in electron-builder: Module 'dmg-license' was not found

Seeking a straightforward method to create an electron app for macOS from a Linux machine. Unfortunately, the electron-builder -m command is not functioning properly. Here is the complete output of the command: electron-builder -m • elec ...

The data is not appearing in the Vuetify data table

I have encountered an issue with the Vuetify data table where it is not displaying any data. Even though it shows that there is 1 row out of 1 displayed, the table body remains empty. Below is my component code: <template> <v-data-table :hea ...

Discovering the current active link and anchor tag details using jQuery in an unordered list

I am currently utilizing jQuery to work with 4 anchor tags inside an unordered list, and I would like to be able to determine the "current active link" when a user performs a search. This way, I can execute my query based on the selected anchor tag. How ca ...

Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs: { "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.creates i ...

How do I use jQuery to animate a height increase where the added height is applied to the top of the element?

I am facing a simple issue that I need help resolving. The problem involves hidden content that, once expanded, needs to have a height of 99px. When collapsed, the container holding this content section#newsletter is set to be 65px in height. If you want ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

Safari causing issues with AJAX requests when using HTTPS

While I'm not an expert in ajax, the request I have is quite simple: $.ajax({ url: "https://62.72.93.18/index.php?a=get_lights", dataType: 'jsonp', success: function (res) { notify ? jsonLightsDone(re ...

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

Unable to process form submission with AngularJS + Stormpath

I am facing an issue with form submission. Even though I believe that the login and password data are being sent correctly, nothing happens when I submit the form. I am attempting to submit the form without using ngSubmit because it is not feasible in my s ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

jticker.js enables autoscroll feature on a mobile device

I'm currently utilizing jticker.js to showcase my data. While everything works fine on larger screens, I'm encountering an issue on mobile devices where the scroll stops once the height of the screen is reached. I would like the scroll to contin ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...