Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does confirm() work in JavaScript

I was thinking about how the native functions in JavaScript work today, and I can across alert() and I figured it must use createElement() or make an element and use innerHTML, but I can't figure out the complete code it would need to create a popup element, and make two buttons, then return true or false based on the one click.
jowes said:

usually JS is async; why is alert special? how and why does it create UI elements in a different way from my own scripts?

Here's the code I have figured out:

function confirm(message) {
    message = message.replace(/"\n"/g, "<br />")
    createElement();
//The create Element is very complicated to create the text box including message. . .
//These two functions are tied to the button's onclick's.
    function clickOkay() {
        valueToReturn = true
        return true;
    }
    function clickCancel() {
        valueToReturn = true
        return false;
    }
    //here, the user hits the button, and sets valueToReturn
    return valueToReturn;
}

But I don't understand how it stops the background script, if accessable, or how createElement() works, (but thats a question for another time)

like image 352
Travis Avatar asked Nov 02 '25 12:11

Travis


1 Answers

alert, confirm, and prompt are all DOM APIs that are implemented by the browser. They do not create DOM elements to represent them, and their functionality cannot be exactly recreated with JavaScript because you cannot force the JavaScript engine to wait for the user to click one of your buttons. You can only come close by requiring a callback that will contain the result of the dialog that you create.

function customConfirm(message, callback) {
    message = message.replace(/"\n"/g, "<br />")
    createElement();
    //The create Element is very complicated to create the text box including message. . .
    function clickOkay() {
        callback(true);
    }
    function clickCancel() {
        callback(false);
    }
}
customConfirm("Hello World!", function (result) {
    console.log(result);
});
like image 94
Kevin B Avatar answered Nov 04 '25 03:11

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!