Thursday, February 23, 2012

jQuery popup boxes plugin

I have recently created a jQuery plugin that mimic behavior of javascript popup boxes: alert, prompt and confirm. The problem that I had with usage of native javascript popup boxes is that it stops the execution of script until user close it. Also, I wanted to separate a code that will be executed if user confirms or cancels the dialog without further inspecting of return value.

With that in mind I created alternative for popup boxes using jQuery plugin and jQuery deferred objects (introduced in jQuery 1.5). Also, to simplify my code all popup boxes are dependable on jQuery UI dialog.

The three methods are:
  • $.alert(messagetitledialogOptions)
  • $.confirm(messagetitledialogOptions)
  • $.prompt(titledefaultValuedialogOptions)
So, to alert some message simply call:

$.alert("Poruka")

Deferred
The beauty of it comes with a usage of deferred object. So if we want some code to be executed only if user confirms it, than we can write something like this:

$.confirm("Changes on this document are not saved. Open a new one anyway?")
  .done(function() {
    // make some ajax call
  })
  .fail(function() {
    $.alert("Pfff... we almost lost this file")
  })

What will happen is that if user clicks OK, the deferred object will be resolved and code under done will be executed. If user clicks cancel or closes the dialog, code under the fail will be executed. So, there is no need for additional if condition. Also, code is cleaner and easier to read and understand.

The same thing can be managed with use of prompt as well.

$.prompt("How much?", 1)
  .done(function(data) {
    $.alert("You have enetered " + data)
  })

This would prompt user to enter value. After that if user clicks OK or presses enter it would run function passed to done and it would provide entered value in data argument.

Dependence:

Source code: