BenM BenM - 1 year ago 243
Javascript Question

Creating custom jQuery function without selector prerequisite

I know that I can create custom jQuery plugins by using the

constructor, and the calling the custom function in JavaScript as

However, for a project I'm currently working on, I need to be able to define a function that does not require a selector to work.This is actually for a MessageBox plugin, which will act in a similar manner to C#'s
class. As such, I would ideally like to create the function as
, and then call it as follows:

var myMessage = $.MessageBox();
and then in turn

Notice the lack of selector brakets in the jQuery reference at the beginning of the function call.

Any advice on the best practice for this would be gratefully received.

Answer Source

This should work:

jQuery.MessageBox = function() {
  var show = function() {
    // something...
  var hide = function() {
    // something...
  return {
    show: show,
    hide: hide
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download