I am fairly new at writing jQuery plugins. Moreover, I am a huge fan of best practice.
I have written a plugin which centers an element inside its parent. I would love some feedback on how I could have written it better.
(function( $ ){
$.fn.verticalCenter = function(options) {
var settings = $.extend({
min: 0, // Minimum width of the viewport for the centering to take effect
max: 10000 // Maximum width of the viewport
}, options);
var center_element = function(element, parent){
var elementHeight = element.height();
parent.css({
position:'relative'
});
element.css({
position: 'absolute',
top: "50%",
marginTop:-elementHeight/2
});
}
var remove_style = function(element, parent){
parent.css({ position:'' });
element.css({ position: '', top: '', marginTop: '' });
}
var determine_action = function(element, parent){
$(window).on('load resize orientationchange', function() {
var windowWidth = window.innerWidth
if (windowWidth > settings.min && windowWidth < settings.max) {
center_element(element, parent);
}
else {
remove_style(element, parent);
}
});
}
return this.each(function(){
var $elementToCenter = $(this);
var $parent = $elementToCenter.parent();
determine_action($elementToCenter, $parent);
});
};
})( jQuery );
The plugin is supposed to be responsive, and it allows the user to pass in viewport min and max values. These values determine if the centering should occur.