I would like to create a JavaScript function similar to confirm()
that shows a dialog (a div with a question and 2 buttons) and returns true
if the user clicks "Ok" or false
otherwise.
Is it possible to do that using JavaScript/jQuery but without plugins (e.g. jQuery UI or Dialog)? Because I'm trying to reduce size and round trip times...
I tried to write this code, but I don't know how to make the function "wait" for the user click.
I would like to use my function in this way:
answer=myConfirm("Are you sure?")
In this way I could use the same function in several contexts, simply changing the question passed as a parameter. This is the same behavior of confirm()
If using jQuery, why not implement jQueryUI? And use the Dialog function as follows:
HTML
Script
jsFiddle
Rather than waiting for the user's input and then returning from the function, it is more common in JavaScript to provide a callback function that will be called when the action you're waiting for is complete. For example:
This could be implemented along the lines of:
This really should be done with a callback. The closest thing to what you're after would be to use a publish and subscribe model with some custom events.
To do so:
When a user clicks the yes button, trigger a custom event called clickedYes. Do the same for "no"
Now we need to "listen" or subscribe for those events and execute the appropriate action in context.
Lets create a hypothetical situation: Your user clicks delete and you want to confirm that choice.
First setup what you want to happen if they click yes:
then what you want to happen if they click no:
So we've setup actions that are listening for clickedYes or clickedNo. Now we just need to show the user the popup so that they have to click yes or no. When they do, they'll trigger the events above.
so your myConfirm() function will just do the following:
So the order would be:
This will allow you to call the function like this myConfirm('Are you sure'); It's not quite what you're after...but I don't think it's possible to do exactly what you want.