I have a function that does some stuff and one thing it does is calculates height/width and applies css top/left for centering. Instead of rewriting the formula more than once, I want to be able to reuse it and pass arguments through it.
I have:
loading.css({
top: (wrapper.height() - loading.outerHeight()) / 2 + 'px',
left: (wrapper.width() - loading.outerWidth()) / 2 + 'px'
});
I want to be able to reuse those 2 formulas and also replace loading with other registered elements.
I have no idea what I’m doing and I’ve tried several things which failed…
I want to be able to call it through something like loading._center();
When the function runs, it appends the loading div and calculates the absolute positioning top and left using the code above. I wanted it to stay centered when the window resizes, so I basically duplicated the code above and wrapped it with a $(window).resize function.
When an error div is shown, since the height/width dimensions are different, I’m calculating top and left again with a similar code. Instead of duplicating the element.css({top: [...], left: [...]}), I just want to do something like…
_center = function() {
var context = $(this);
context.css({
top: (wrapper.height() - context.outerHeight()) / 2 + 'px',
left: (wrapper.width() - context.outerWidth()) / 2 + 'px'
});
};
loading._center();
I was close. I forgot to return the calculation.. I now have:
_center = function($this) {
$this.css({
top: (wrapper.height() - $this.outerHeight()) / 2 + 'px',
left: (wrapper.width() - $this.outerWidth()) / 2 + 'px'
});
};
_center(loading);
you could provide a function for the 2nd argument:
Here’s the documentation of the .css().