Creating a personalized confirmation function using JavaScript

Here is a function I've created to generate a confirmation box.

The issue I'm facing is that the function doesn't wait for the user to click before returning true/false based on the onclick events.

So, how can I solve this?


function Confirmation(title, message, confirm_button_value) {
  if (
    typeof title !== "undefined" ||
    typeof message !== "undefined" ||
    typeof confirm_button_value !== "undefined"
  ) {
    if (title !== "" || message !== "" || confirm_button_value !== "") {
      var confirmation;

      var confirmation_box = document.createElement("div");
      confirmation_box.classList.add("confirmation_box");

      var title_container = document.createElement("div");
      title_container.classList.add("confirmation_box_title");
      title_container.innerHTML = title;
      confirmation_box.append(title_container);

      var message_container = document.createElement("div");
      message_container.classList.add("confirmation_box_message");
      message_container.innerHTML = message;
      confirmation_box.append(message_container);

      var buttons_container = document.createElement("div");
      buttons_container.classList.add("confirmation_box_buttons");

      var confirm_button = document.createElement("span");
      confirm_button.classList.add("confirmation_box_confirm_button");
      confirm_button.innerHTML = confirm_button_value;
      buttons_container.append(confirm_button);

      var cancel_button = document.createElement("span");
      cancel_button.classList.add("confirmation_box_cancel_button");
      cancel_button.innerHTML = "Cancel";
      buttons_container.append(cancel_button);

      confirmation_box.append(buttons_container);

      document.body.append(confirmation_box);

      confirm_button.onclick = function () {
        confirmation = true;
      };

      cancel_button.onclick = function () {
        confirmation = false;
      };

      return confirmation;
    }
  }
}

(I am interested in straightforward solutions.)

Answer №1

There are multiple solutions to this problem

One approach is the traditional callback method

function Confirmation(title, message, confirm_button_value, callback) {
    if (typeof title !== "undefined" || typeof message !== "undefined" || typeof confirm_button_value !== "undefined") {
        if (title !== "" || message !== "" || confirm_button_value !== "") {
            
            // code snippet omitted for brevity
            
            confirm_button.onclick = function () {
                callback(true);
            };

            cancel_button.onclick = function () {
                callback(false);
            };
            return; 
        }
    }
    throw "Bad arguments";
}

example of usage

try {
    Confirmation("title", "message", "button value", function(result) {
        // handle the outcome here
    });
} catch(err) {
    // error handling goes here
}

Another approach involves using Promises, which essentially serve as enhanced callbacks

function Confirmation(title, message, confirm_button_value) {
    return new Promise((resolve, reject) => {
        if (typeof title !== "undefined" || typeof message !== "undefined" || typeof confirm_button_value !== "undefined") {
            if (title !== "" || message !== "" || confirm_button_value !== "") {
                
                // code snippet omitted for brevity
                
                confirm_button.onclick = function () {
                    resolve(true);
                };

                cancel_button.onclick = function () {
                    resolve(false);
                };
                return; 
            }
        }
        reject("bad arguments");
    });
}

example of usage with Promises

Confirmation("title", "message", "button value")
    .then(result => {
        // handle the outcome here
    })
    .catch(err => {
        // handle any errors here
    })

Alternatively, you can utilize async/await - a more user-friendly syntax built upon Promises

The core confirmation function remains unchanged, only the implementation differs

example of usage - ensure it's within an async function or at the top level of a module

try {
    const result = await Confirmation("title", "message", "button value");
    // process the result here
} catch(err) {
    // handle any errors here
}

Answer №2

Include a callback function in the parameters. Invoke the callback after a user clicks on any button with a specified value.

function UserConfirmation(title, message, confirmText, executeCallback) {
  if (
    typeof title !== "undefined" ||
    typeof message !== "undefined" ||
    typeof confirmText !== "undefined"
  ) {
    if (title !== "" || message !== "" || confirmText !== "") {

      var confirmationBox = document.createElement("div");
      confirmationBox.classList.add("confirmation_box");

      var titleContainer = document.createElement("div");
      titleContainer.classList.add("confirmation_box_title");
      titleContainer.innerHTML = title;
      confirmationBox.append(titleContainer);

      var messageContainer = document.createElement("div");
      messageContainer.classList.add("confirmation_box_message");
      messageContainer.innerHTML = message;
      confirmationBox.append(messageContainer);

      var buttonsContainer = document.createElement("div");
      buttonsContainer.classList.add("confirmation_box_buttons");

      var confirmButton = document.createElement("span");
      confirmButton.classList.add("confirmation_box_confirm_button");
      confirmButton.innerHTML = confirmText;
      buttonsContainer.append(confirmButton);

      var cancelButton = document.createElement("span");
      cancelButton.classList.add("confirmation_box_cancel_button");
      cancelButton.innerHTML = "Cancel";
      buttonsContainer.append(cancelButton);

      confirmationBox.append(buttonsContainer);

      document.body.append(confirmationBox);

      confirmButton.onclick = function () {
        executeCallback(true);
      };

      cancelButton.onclick = function () {
        executeCallback(false);
      };

    }
  }
}

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

Storing JSON data using Vuex

As I am delving into the world of Vuex store used with vue.js, I find myself wanting to implement it in a specific scenario. 1. Is STATE referring to any data, whether static or dynamic, that is provided by the server or stored in a JSON format? TEMPLATE ...

Learn how to implement a captivating animation with JavaScript by utilizing the powerful Raphael Library. Unleash the animation by triggering it with either

My desire is to indicate this movement by triggering a mouse click or drag to the desired location. let myDrawing = Raphael(10,10,400,400); let myCircle = myDrawing.circle(200,200,15); myCircle.attr({fill:'blue', stroke:'red'}); let my ...

Techniques for triggering JavaScript on elements that have been dynamically loaded via Ajax

When it comes to ensuring that a certain functionality works both when the document is ready and after an Ajax call, there are some considerations to keep in mind for optimal performance. An approach I found effective involves defining the desired code wi ...

Having trouble with blurriness in the SVG image loading on three.js

Currently, I am using loadTexture (THREE.ImageUtils.loadTexture('/images/areaYellow.svg')) to load SVG images. However, when I zoom in on the image, it becomes blurred. Is there a way to load the image without this blurriness? I am currently work ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

navigating a collection of objects and retrieving individual property values

I am having trouble extracting values from an array of objects, specifically only the values from the first object in each sub-array. Here is how my array of objects looks: items [ [ {id: 1, title: "title1", imgUrl: "https://someimage1"}, {id: 2 ...

What is the process for setting up a vertical carousel in Bootstrap 5 with a stationary previous image?

Looking for assistance with my vertical carousel project. Is there a way to create a vertical carousel in bootstrap 5 with the previous image fixed? I found a slider on this website: zara.com/jp/en/ I want to maintain the previous image in a fixed posit ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

The system detected a missing Required MultipartFile parameter in the post request

Can anyone explain to me why I am encountering the error mentioned above? I am unable to figure out the reason. Below is my code, please review it and suggest a solution for fixing this error. The objective is to upload multiple files to a specific locatio ...

Is there a way to eliminate the black seam that is visible on my floor mesh that has been separated? I am utilizing A

I recently imported a large .glb file into AFrame. The model has baked textures and the floor is divided into multiple mesh parts for improved resolution. However, I am facing an issue where black seams appear on the separated parts of the floor, only dis ...

Is it possible to pass a class method to an onClick event from within the render method in ReactJS?

Excuse my lack of experience, but I haven't been able to find a solution to this yet. I am attempting to utilize a class method as a callback for the onClick event in my JSX. Below is the code for my App component: import React from 'react&apo ...

Are you on the lookout for an Angular2 visual form editor or a robust form engine that allows you to effortlessly create forms using a GUI, generator, or centralized configuration

In our development team, we are currently diving into several Angular2< projects. While my colleagues are comfortable coding large forms directly with Typescript and HTML in our Angular 2< projects, I am not completely satisfied with this method. We ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

Employing passport-steam alongside sails-generate-auth

As I develop my SailsJS application, I am aiming for users to authenticate solely through Steam. I utilized `sails-generate-auth` to set up some boilerplate code with sails routes, but integrating passport-steam has proven challenging. If you are interest ...

It seems like KineticJS is removing elements from the canvas that I would prefer to keep

My website features an HTML5 canvas where I showcase a variety of images, text, and shapes using JavaScript functions. The text and shapes are created with the following JavaScript functions: function drawGameElements(){ /* Draw a line for the ' ...

I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text. var xmlHttp = new XMLHtt ...

Tips for comparing and adding a field to a sub-array within an object

I have a scenario where I have two objects. The first object contains name and id, while the second object has some fields along with the id field from the first object. For Example: FirstObj = [{ _id: '48765465f42424', Name : 'Sample& ...