Question

I'm writing a jQuery plugin and am trying to use the $(this) selector in one of the parameters, but it's undefined.

Here's my code:

$('.foo').loadMore({
    onScreen: function() {
        $(this).css('background-color', 'red');
    }
})

And here's the code in my plugin:

$.fn.loadMore = function( options ) {

    var settings = $.extend({
        onScreen: function(){}, 
    }, options);

    return this.each(function(index, ele) {
        settings.onScreen();
    });
};
Was it helpful?

Solution

You have to call onScreen with the correct this value:

settings.onScreen.call(this);

If you want to be more in line with the built-in jQuery methods, you can pass the index and element as well:

settings.onScreen.call(this, index, this);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top