user3142418
user3142418

Reputation: 372

Why won't my custom function work?

When creating my own jQuery method, why does this work:

(function($){
    $.fn.test = function() {
        return this.each(function(){
            $(this).html("Hi there");
        });
    } 
})(jQuery);
$(document).ready(function(){
    $("body").click(function(){
        $(this).test().css("color", "orange");
    });
});

But this does not?

(function($){
    $.fn.test = function() {
        return this.each(function(){
            $(this).html("Hi there");
        });
    } 
    $("body").click(function(){
        $(this).test().css("color", "orange");
    });
})(jQuery);

I've tried replacing $ with jQuery but it still doesn't work. It only seems to work within a separate doc.ready function, can anyone explain why?

Thanks!

Upvotes: 1

Views: 52

Answers (1)

Sumner Evans
Sumner Evans

Reputation: 9155

Your second snippet isn't working as expected because

(function($) {...})(jQuery)

is run before the document is ready.

By wrapping your

$('body').click(function () {...})

inside a

$(document).ready(function() {...})

you are telling jQuery to run

$('body').click(function () {...})

after the page has loaded.


What you (probably) want to do instead:

$(document).ready(function() {
    $.fn.test = function() {
        return this.each(function() {
            $(this).html("Hi there");
        });
    }
    $("body").click(function() {
        $(this).test().css("color", "orange");
    });
});

This will run both the

$.fn.test = function() {...}

and the

$("body").click(function() {...}

after the document is ready (which is basically when the page is fully loaded, it's a bit different, but it would not be constructive to expound upon that here).

Upvotes: 2

Related Questions