bflemi3
bflemi3

Reputation: 6790

How to reference calling element in custom plugin

I am creating a simple jQuery plugin and I'm trying to reference the calling element in my shrink() function. I know that if I don't pass the element then this will refer to window but is there a way to refer to the element that called the jQuery plugin? If not, then how would I pass this in the callback of $(window).on('resize', shrink);?

$(function ($) {
    $.fn.shrinkIt = function (options) {
        var settings = $.extend({
            className: "shortened",
            maxWidth: 800
        }, options);

        var shrink = function (elem) {
            var $this = $(elem);
            var viewerWidth = $('.header').width();
            if (viewerWidth > 800) {
                $this.removeClass(settings.className);
            } else {
                $this.addClass(settings.className);
            }
            $this.css('visibility', 'visible');
        };

        return this.each(function () {
            shrink(this);
            $(window).on('resize', shrink); // how to get 'this' to shrink() function??
        });
    };

    $('.lessonDocumentType').shrinkIt();
})(jQuery);

Upvotes: 0

Views: 130

Answers (2)

Luca Rainone
Luca Rainone

Reputation: 16468

Change your approach. Instead of define a listener for each element, attach one time the listener and manage all elements:

$(function ($) {
    $.fn.shrinkIt = function (options) {
        var settings = $.extend({
            className: "shortened",
            maxWidth: 800
        }, options);

        var $els = $(this);
        $(window).on('resize', shrink);
        function shrink() {
            $els.each(function() {
                var $this = $(this);
                var viewerWidth = $('.header').width();
                if (viewerWidth > 800) {
                    $this.removeClass(settings.className);
                } else {
                    $this.addClass(settings.className);
                }
                $this.css('visibility', 'visible');
            });
        };
        return this;

    };

    $('.lessonDocumentType').shrinkIt();
})(jQuery);

Upvotes: 1

ori
ori

Reputation: 7847

Put var $this = $(this); inside the first function ($.fn.shrinkIt).

Any inner function within that function can now refer to $this.

Upvotes: 1

Related Questions