Skip to content

Instantly share code, notes, and snippets.

@bredfern
Forked from monkeymonk/jquery.scrollToTop.js
Created July 13, 2017 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bredfern/c15b9c2c90ff92de4b85d80d9c2de779 to your computer and use it in GitHub Desktop.
Save bredfern/c15b9c2c90ff92de4b85d80d9c2de779 to your computer and use it in GitHub Desktop.
ES6 jQuery plugin definition
import $ from 'jquery';
import plugin from './plugin';
class ScrollToTop {
constructor(element, options) {
const $element = $(element);
$(window).scroll(function () {
if ($(this).scrollTop() > options.offset) {
$element.fadeIn();
} else {
$element.fadeOut();
}
});
$element.click(function (e) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, options.speed);
});
}
}
ScrollToTop.DEFAULTS = {
offset: 100,
speed: 500,
};
plugin('ScrollToTop', ScrollToTop);
import $ from 'jquery';
/**
* Generate a jQuery plugin
* @param pluginName [string] Plugin name
* @param className [object] Class of the plugin
* @param shortHand [bool] Generate a shorthand as $.pluginName
*
* @example
* import plugin from 'plugin';
*
* class MyPlugin {
* constructor(element, options) {
* // ...
* }
* }
*
* MyPlugin.DEFAULTS = {};
*
* plugin('myPlugin', MyPlugin');
*/
export default function plugin(pluginName, className, shortHand = false) {
let dataName = `__${pluginName}`;
let old = $.fn[pluginName];
$.fn[pluginName] = function (option) {
return this.each(function () {
let $this = $(this);
let data = $this.data(dataName);
let options = $.extend({}, className.DEFAULTS, $this.data(), typeof option === 'object' && option);
if (!data) {
$this.data(dataName, (data = new className(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
};
// - Short hand
if (shortHand) {
$[pluginName] = (options) => $({})[pluginName](options);
}
// - No conflict
$.fn[pluginName].noConflict = () => $.fn[pluginName] = old;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment