I’ve wanted to write a jQuery plug-in for a long time, but I didn’t want to write one just for the exercise.
Last night I was messing around with overriding native JavaScript functions – among those the alert-function – and it hit me: why not write a plug-in for jQuery which overrides and personalizes alert messages without the need to change any existing code? And while I was at it, integrate the plug-in with jQuery UI and leverage the functionality of the Dialog widget?
So I did. And here’s what I came up with
Note: my WordPress theme seems to be interfering with the jQuery UI theme; breaking the styles on the close-button in the dialog.
The plug-in code
jQuery.altAlert = function (options)
{
var defaults = {
title: "Alert",
buttons: {
"Ok": function()
{
jQuery(this).dialog("close");
}
}
};
jQuery.extend(defaults, options);
delete defaults.autoOpen;
window.alert = function ()
{
jQuery("<div />", { html: arguments[0].replace(/\n/, "<br />") }).dialog(defaults);
};
};
And here’s how you use it… it’s pretty simple, really
$(function ()
{
$.altAlert();
});
After calling the plug-in constructor, all calls to the native alert-function will pop up a jQuery UI dialog instead of the boring standard dialog. Neat, huh?
My plug-in leverages the jQuery UI Dialog widget
And because my plug-in leverages jQuery UI, my plug-in…
- inherits solid code that has undergone rigorous testing
- generates solid markup that has been tested and looks the same in all A-grade browsers
- fully supports the jQuery UI Themeroller
On top of that: all the functionality available in the jQuery UI Dialog widget is available in my plug-in. This means that you can override the standard functionality of my plug-in – just like you would, using the jQuery UI Dialog widget – and change it’s default behavior:
$(function ()
{
$.altAlert(
{
modal: true,
closeOnEscape: false,
title: "Dang!... Stuff happend!",
buttons: {
"Ok": function()
{
window.location = "error.html";
}
}
});
});
In the above example, the code effectively locks down a page, preventing user-input, while the browser loads an error page.
In a few days time…
I will create a project on Google Code, and put up some live usage-examples… In the meantime; feel free to leave comment and tell me what you think.
Update…
I’ve added my plug-in to the endless list on the jQuery website. Here’s a direct link.