views:

4616

answers:

5

I want to write something that acts just like confirm() in javascript, but I want to write it myself so I can skin the dialog box. In having trouble thinking through how I would basically force the javascript thread to wait until the user responds and then return true or false.

+5  A: 

If I were you, I would look at one of the popular javascript libraries. Most contain some sort of modal dialog.

A couple I found for JQuery are jqModal and SimpleModal.

When you build the modal dialog, you will have to tie events to the buttons, so you would do something like:

function askUserYesOrNo() {
  var myDialog = $('<div class="mydialog"><p>Yes or No?</p><input type="button" id="yes" value="Yes"/><input type="button" id="no" value="No"/></div>');
  $("#yes").click(handleYes);
  $("#no").click(handleNo);
  myDialog.modal(); //This would have to be replaced by whatever syntax the modal framework uses
}

function handleYes() {
  //handle yes...
}

function handleNo() {
  //handle no...
}
Chris Marasti-Georg
So is the takeaway here I can no longer write code like "if(confirm("text")) { //handleYes } else { //handle No } //other stuff after that? I'd like to be able to use it the same way as you use confirm.
Bialecki
both of the plugins linked to have examples of overriding the confirm()
Geoff
AFAIK, javascript threads are run synchronously with the UI thread. If you have ever run into a long running script that froze your browser, you've seen this. This may not be the case in Chrome, for example, but it is in most browsers in use.
Chris Marasti-Georg
+2  A: 

You really want to use a framework for this, because of the number of weird cross-browser issues that you'll encounter trying to build it yourself.

I've had good results using jqModal, a plugin for the jQuery framework that lets you define modal dialogs, but it's by no means the only option; try Googling jquery modal or yui modal for some alternatives.

Dylan Beattie
A: 

You could use window.showModalDialog (mozilla), but it's a non-standard function introduced by Internet Explorer. Now it's also supported in Firefox 3 and Safari (I'm not sure which version, but at least 3.1 and highter, but not the iPhone).

doekman
+1  A: 

For Mootools, there are moo.rd's Custom.Confirm and Windoo.Confirm for your reference.

cheeaun