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);
Put
var $this = $(this);inside the first function ($.fn.shrinkIt).Any inner function within that function can now refer to
$this.