JSFiddle - React, Tailwind, and code Playground
HTML
<button id="add">Red</button><button id="remove">Not red</button>
<br>
<br>
<br>
<h1>Red while scrolling</h1>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
CSS
.myPluginactive {
color: red;
}
JavaScript
(function($, window, undefined) {
var pluginName = 'myPlugin',
jqCollection = $(),
events = {
scroll: 'scroll.' + pluginName
},
className = pluginName + 'active',
timeout;
function scroll() {
if(jqCollection.closest('body').length === 0) {
//This is advisable in case some other javascript/DOM activity has removed all elements in jqCollection.
// Thanks to selected answer at :
// http://stackoverflow.com/questions/4040715/check-if-cached-jquery-object-is-still-in-dom
jqCollection = $();
$(window).off(events.scroll);
} else {
jqCollection.addClass(className);
clearTimeout(timeout);
timeout = setTimeout(function() {
jqCollection.removeClass(className);
}, 100);
}
}
methods = {
add: function(jq) {
jqCollection = jqCollection.add(jq);
if(jqCollection.length > 0) {
$(window)
.off('.' + pluginName)
.on(events.scroll, scroll)
}
},
remove: function(jq) {
jqCollection = jqCollection.not(jq);
if(jqCollection.length === 0) {
$(window).off('scroll.' + pluginName);
}
}
};
$.fn[pluginName] = function(method) {
method = method || 'add';
if(methods[method]) {
methods[method](this);
};
return this;
};
})(jQuery, window);
$("#add").click(function() {
$("h1").myPlugin();
$("button").prop('disabled',false).filter(this).prop('disabled',true);
}).trigger('click');
$("#remove").click(function() {
$("h1").myPlugin('remove');
$("button").prop('disabled',false).filter(this).prop('disabled',true);
});