mpen
mpen

Reputation: 282865

How to design a jQuery plugin that depends on the page having been loaded?

I'm writing a jQuery plugin that starts off like this:

$.fn.kewTip = (function() {
    var $kewtip = $('<div></div>').css({'position':'absolute','zIndex':2147483647}).attr({'class':'kewtip'}).hide().appendTo('body');

You will notice that it immediately appends an element to the page body, but it can't do that until the DOM is ready, which means the plugin can't be defined until the DOM is ready either.

However, I'd ideally like calls to $('xxx').kewTip() to not fail if they try calling it outside of $(document).ready({ ... }). So how do I get around this?

My plugin depends on this element existing, so how do I define it before the DOM is ready?

Upvotes: 1

Views: 42

Answers (2)

Felix Kling
Felix Kling

Reputation: 816404

If all you want to do is to be certain that the div exists when the plugin method is called the first time, then just create it. In order to work with the element (append elements, event handlers) it does not have to be added to the DOM.

Then, independently, add the element to body when the DOM is loaded.

For example:

$.fn.kewTip = (function() {
    // create element
    var $kewtip = $('<div />', {
        'class': 'kewtip',
        'style': 'position:absolute;zIndex:2147483647;display:none'
     });

    // add to DOM once it is ready
    $(function() {
        $kewtip.appendTo('body');
    });

    return function() {
        // here you can do whatever with `$kewtip` no matter whether it was 
        // already appended to body or not
    }
}());

(I assume you have a self invoking function there)

Upvotes: 4

mpen
mpen

Reputation: 282865

Based on Joy's suggestion, I came up with this:

$.fn.kewTip = (function() {
    var $kewtip = $();
    $(function() {
        $kewtip = $('<div></div>').css({'position':'absolute','zIndex':2147483647}).hide().appendTo('body');
    });

$() just gives an an empty jQuery object so the rest of the code doesn't fail catastrophically before it's ready.

Upvotes: 0

Related Questions