Skip to content

Instantly share code, notes, and snippets.

@itmammoth
Last active May 26, 2019 08:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itmammoth/a55a7240ec069f122ced94f151d8e281 to your computer and use it in GitHub Desktop.
Save itmammoth/a55a7240ec069f122ced94f151d8e281 to your computer and use it in GitHub Desktop.
jQuery plugin that provides auto-extension (currently `width` is only supported) to elements
/**
* ex)
* <input type="text" class="jq-auto-adjust" data-base-width="60" data-base-window-width="1280">
* $('.jq-auto-adjust').autoAdjust();
*/
(function($) {
'use strict';
var methods = {
init: function(options) {
var settings = $.extend({
baseWidth: 'current', // number(px) or 'current'
baseWindowWidth: 'current', // number(px) or 'current'
}, options);
return this.each(function() {
var $this = $(this);
var autoAdjust = new AutoAdjust($this, mergeOptions($this, settings));
autoAdjust.observe();
$this.data('plugin_auto_adjust', autoAdjust);
});
},
off: function() {
return this.each(function() {
var autoAdjust = $(this).data('plugin_auto_adjust');
autoAdjust.stopObserving();
});
},
};
var mergeOptions = function($el, settings) {
return $.extend({}, settings, $el.data());
};
$.fn.autoAdjust = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.autoAdjust');
}
};
var AutoAdjust = (function() {
var NAMESPACE = '.auto_adjust';
var AutoAdjust = function($el, settings) {
this.$el = $el;
this.$window = $(window);
this.baseWidth = settings.baseWidth === 'current' ? this.$el.width() : settings.baseWidth;
this.baseWindowWidth = settings.baseWindowWidth === 'current' ? this.$window.width() : settings.baseWindowWidth;
};
$.extend(AutoAdjust.prototype, {
observe: function() {
this.$window.on('resize' + NAMESPACE, this._bind('onResize'));
this.adjust();
},
stopObserving: function() {
this.$window.off(NAMESPACE);
},
onResize: function(e) {
this.adjust();
},
adjust: function() {
var diff = this.$window.width() - this.baseWindowWidth;
var width = this.baseWidth + diff;
if (width < 1) width = 1;
this.$el.width(width);
},
_bind: function(funcName) {
var that = this;
return function() { that[funcName].apply(that, arguments) };
},
});
return AutoAdjust;
})();
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment