Question

I am developing the MooTools confirm box function. In which I have two buttons which are OK and CANCEL.

So I want return TRUE on click of OK and return FALSE on click on CANCEL.

Here is my function code.

function confirm_box(title, text)
{
    var className = 'msgAlert info';
    var defaut_title ='Information';

    // Placing the Overlay
    var overlay = new Element('div', {'class':'msgAlert_overlay'});
    $$('body').adopt(overlay);

    // Placing the Main Div With class name
    var main_box  = new Element('div', {'class': className});
    $$('body').adopt(main_box);

    var content_div = new Element('div', {'class':'msgAlert_popup'});
    //<a href="javascript:;" class="msgAlert_close"></a>
    if(title == '')
        title=defaut_title;
    content_div.set('html','<div class="msgAlert_header"><h4>'+title+'</h4></div><div class="msgAlert_content">'+text+'</div>');
    main_box.adopt(content_div);

    content_div.getChildren('a.msgAlert_close');

    var footer_div = new Element('div',{'class':'msgAlert_footer'});
    var ok_btn = new Element('button');
    ok_btn.addEvent('click', function(){
        main_box.fade(0);
        //overlay.fade(0);
        (function(){main_box.dispose(); overlay.dispose(); }).delay(350);
        return true;
    });

    var cancel_btn = new Element('button');
    cancel_btn.addEvent('click', function(){
        main_box.fade(0);
        //overlay.fade(0);
        (function(){main_box.dispose(); overlay.dispose();}).delay(350);
        return false;
    });

    ok_btn.set('html','Ok');
    cancel_btn.set('html','Cancel');
    footer_div.adopt(ok_btn);
    footer_div.adopt(cancel_btn);
    main_box.adopt(footer_div);
    ok_btn.focus();
}

I have placed return TRUE and FALSE on click on respective buttons.

Can any suggest in which way I have to go so I can access my function just like the JS confirm box:

Just Like :

if(confirm_box(title, text))
{
 alert('Yes');
}
else
{
 alert('No');
}
Was it helpful?

Solution

this is not going to work. basically, you can use the native

if (confirm("are you sure")) { ... } else { ... }

which is fine, because it is blocking the UI thread...

when you want to replicate a confirm box, you need to work with an event callback method instead as your function will NOT have a return value.

in pseudo code, this will be:

var confirm_box = function(title, text, onConfim, onCancel) {

    ... 
    confirmEl.addEvent("click", onConfirm);

    cancelEl.addEvent("click", onCancel);
};


confirm_box("Are you sure?", "Please confirm by clicking below", function() {
    alert("yes");
}, function() {
    alert("no");
});

in the context of mootools and Classes, you may want to do a confirm class which works with events instead. If you want an example, give me a shout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top