Creating a custom JavaScript confirm function without relying on external libraries

I am currently working on creating a custom confirmation function from scratch, without using any libraries. This function is designed to display a modal window with buttons that will return either true or false.

if(getConfirmation) {
    do something
} else {
    do something
}

Most of the implementation is complete except for handling button interactions. The issue I am facing is that I am unable to halt the code execution in the same manner as the default confirm function does. Upon clicking the button labeled Click me at line 56, I receive either undefined or Cancel instead of properly executing the getConfirmation function.

const button = document.querySelector('#abc')
button.addEventListener('click', (e) => {
    // usage
    if(getConfirmation(options)) {
        console.log('Ok')
    } else {
        console.log('Cancel')
    }
})

The current structure of the code seems fine, but I suspect the issue lies in how I am detecting button clicks.

function getConfirmation(options) {
    const element = createElement('confirm_window')
    element.insertAdjacentHTML('afterbegin', getTemplate(options))
    document.body.appendChild(element)
    
    element.querySelectorAll('button').forEach(button => {
        button.addEventListener('click', function(e) {
            const result = options.buttons.find(b => b.name === e.target.name).result
            document.body.removeChild(element)
            return result
        })
    })
        
}

My question is: How can I ensure that the function waits until any button click occurs (either Confirm or Cancel)?

For a demonstration, you can view the code here: https://codepen.io/hamper_/pen/eYzNXqN?editors=1010

Answer №1

You should modify your code slightly and utilize a Promise object

function showConfirmationDialog(options) {
    return new Promise(resolve => {
        const dialogElement = createDialogElement('confirmation_box')
        dialogElement.insertAdjacentHTML('afterbegin', getTemplate(options))
        document.body.appendChild(dialogElement)

        dialogElement.querySelectorAll('button').forEach(button => {
            button.addEventListener('click', function(e) {
                const result = options.buttons.find(b => b.name === e.target.name).result
                document.body.removeChild(dialogElement)
                resolve(result);
            })
        });
    };      
}
showConfirmationDialog(options)
    .then(result => {
        if (result) {
            console.log('Confirmed')
        } else {
            console.log('Cancelled')
        }
    });

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

How to position an absolute element beneath a fixed element

My website is experiencing a problem where the fixed header is overlapping an absolute paragraph on this page. Does anyone know how to resolve this issue? ...

What is the reasoning behind assigning initial values to this function variable?

Upon logging arr early in this function, the displayed values are as follows. I initially anticipated it would display [[null,null],[null,null]]; however, it instead shows the value of arr once the function is completed. updateBounds() { let arr = [ ...

What is the best way to add an event listener to the parent component in ReactJS?

I am currently working on creating a customized context menu that will appear when the user right-clicks on a specific area of my webpage, while still allowing the browser's default context menu to be displayed on other parts of the page. From the pa ...

Updating the image source with a span tag: A step-by-step guide

I am attempting to update the img src value by utilizing the data from the span tag Although I have successfully retrieved the value for the span tag, I am struggling to find a method to change the img src value The issue lies in the fact that the span tag ...

Issue encountered while fetching data using jQuery AJAX request through PHP proxy

Currently, I am in the process of interviewing for a company and they have assigned me a take-home project with no time limit to finish. One specific requirement is to utilize a PHP API proxy to bypass CORS restrictions for their API. I am only allowed to ...

What is the best way to invoke a Javascript function within the same file using PHP?

I am facing an issue with my PHP file named "PhpCallJavascript". I am attempting to call the function CreateSVG() from within the PHP code. However, it seems that it is not working. Do I need to incorporate AJAX here? Or perhaps there is another solutio ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click. The desired behavior is that clicking on the login button should activate th ...

Is there a way to make a text area box visible using JavaScript?

Currently, I am developing an automation script in Python using Selenium. My objective is to make a textarea box visible, as I need to insert some arguments into it. Here is the code snippet that I am utilizing: element = driver.find_element_by_id('g ...

express.js loop execution timing issue

My current code is not waiting for the loop to finish before printing {"personalchats":[]} I need to send after the for loop has completed. How can I fix this issue? connection.query("SELECT * FROM personalchat WHERE user1ID = ? OR user2ID = ?", [userID, ...

Handling null reference exceptions when using the async await pattern

I keep encountering NullReferenceExceptions in a webforms project I am currently managing. The tricky part is that there is no stacktrace available for this exception, as none of my code seems to be causing it. https://i.sstatic.net/CoKFN.png Unfortunatel ...

Capturing screenshots with Selenium in Node.js is proving to be quite sluggish

My current project involves using Selenium with Mocha in Node.js for UI testing on a website. I want to capture screenshots after each test to review and share the results visually. The challenge arises when there are AJAX calls and JavaScript animations ...

Locating a specific value from an href using BeautifulSoup and regular expressions

I am working with the code below and need to extract the value at the end of the href. Is there a way to use BeautifulSoup/Regex to extract the href and find values after page=? from bs4 import BeautifulSoup import requests import json import re request ...

Steps for Adding a class or Id to an Ext.Msg.alert box

Is there a way to customize the style of a specific Ext alert box without affecting all alert boxes? Can someone please explain how to assign a class or ID to an Ext.Msg.alert box? Ext.Msg.alert('Status', 'Changes saved successfully.' ...

"Adjusting the height of a div element while considering the

I have 2 elements with different heights and I want to make them equal: var highestEl = $('#secondElement').height(); $('.element').first().height(highestEl); I understand that the second element is always taller than the first one. W ...

Using both strings and numbers in a Javascript array to simplify multidimensional reduction

I understand the concept of reduce, but I am struggling with a multidimensional array. Can someone help me with transforming this: y = [['x', 0.5], ['x', 0.5], ['z', 2], ['z', 2]]; into this: y = [['x', 1] ...

What are some alternative ways to begin a photo album besides always using the first image

I have a gallery with 5 thumbnail images previewed, but there are more photos in the gallery. Instead of cluttering my code and hiding them with CSS, I am seeking an alternative solution. Below is my current HTML code: <div id="start_slides2"> ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

The synchronicity of server and client clicking is not functioning properly

When button1 is clicked, a server-sided code Button1_Click is executed to submit data into a database. On the other hand, SubmitForm() is client-sided code. How do I make both work when pushing the button named button1 (my submit button)? The code provided ...

Making a POST request using axios in a MERNStack application

After successfully using the express router to add articles with Postman, I encountered an issue when trying to send article information through Axios to MongoDB. Despite no errors appearing in the console, there was a message stating "SharedArrayBuffer ...