I have the following jQuery plugin code to do something on window load or scroll:
Note: I simplified the code for the example.
;(function ($, window, document, undefined) {
'use strict';
$.scrollFn = function (el, options) {
var base = this;
// jQuery and DOM of element
base.$el = $(el);
base.el = el;
// Cached
base.$win = $(window);
base.$doc = $(document);
// Initialize
base.init = function () {
base.options = $.extend({}, $.scrollFn.defaultOptions, options);
};
// Scroll handler
base.scrollHandler = function () {
console.log('scrolled or loaded');
console.log(base.options.exampleOption);
};
// On scroll and load
base.$win.on('scroll load', base.scrollHandler);
};
$.scrollFn.defaultOptions = {
exampleOption: "Test"
};
$.fn.scrollFn = function (options) {
return this.each(function () {
(new $.scrollFn(this, options));
});
};
})(jQuery, window, document);
And in another JS I am initializing the scroll function:
$(document).ready(function() {
$('.example').scrollFn({
exampleOption: "Hello world"
});
});
The issue: It is picking up window scroll but not load. When the window loads I do not see the console return scrolled or loaded. It shows only when I scroll.
How can I make load work as well?
I tried (inside scrollFn):
$(window).on('scroll load', base.scrollHandler);
base.$doc.on('scroll load', base.scrollHandler);
$(document).ready(function() {
base.$win.on('scroll load', base.scrollHandler);
});
They do not work.
I had to simply add base.scrollHandler in the init function. I will except any other answer providing more info or a better solution if possible.