Noah Passalacqua
Noah Passalacqua

Reputation: 802

Plugin not recognizing "this" jQuery

I am trying to get my plugin to recognize the element which it is called from such as:

(function($) {
    $('#element').myPlugin({});
})($)

On a different page -

(function($) {
    $.fn.myPlugin = function(settings) {
        var element = $(this);
        $.post('connection.php',{},
            function(output) {
                element.html(output);
            });
    }
})($)

But it for some reason is not working.. i am puzzled

HTML page:

<body>
    <div id="element">adsf</div>
</body>

Upvotes: 0

Views: 75

Answers (2)

asawyer
asawyer

Reputation: 17808

I think what's throwing you off is that this:

(function($) {
    $('#element').myPlugin({});
})($)

Is not the same as this:

$(function(){
    $('#element').myPlugin({});
});

So everything was working, but the DOM element didn't exist yet as you expected it to.

Upvotes: 1

RestingRobot
RestingRobot

Reputation: 2978

Your function is being called before the DOM is loaded. Try adding

   $(document).ready(function(){...your code..});

Upvotes: 2

Related Questions