There are too many things you missed checking.
First
Your $(this);
contains an array of elements because your selector is img
$("img").middleify();
Yet you are storing values like this :
var i = $(this);
var f = i.parent();
Second
var wh = i.height() == i.width() ? f.width() < f.height() : i.width() > i.height();
var hw = i.height() == i.width() ? f.height() < f.width() : i.height() > i.width();
You don't need to have this kind of conditions, it really does confuse me. How about just setting the width:100%
then height: auto
since your container has bigger width
than it's height.
Third
return i.css({position: "relative", "z-index": 2, width: hw ? "100%" : "auto", height: wh ? "100%" : "auto", top: "50%", right: "50%", "margin-right": 0 - (i.width()) / 2, "margin-top": 0 - (i.width() / 2)});
You are computing the width
and height
of the element which you haven't set those values yet. It's more likely it will get the default values.
To fix that you have to set the width
and height
first and separately to the computation
"margin-right": 0 - (i.width()) / 2, "margin-top": 0 - (i.width() / 2)});
Putting them together
$.fn.extend({
middleify: function(){
var i = $(this);
$.each(i, function(index, value) {
var elm = $(value);
var f = elm.parent();
elm.css({position: "relative", "z-index": 2, width: "100%", height:"auto", top: "50%", left: "50%"});
elm.css({"margin-left": 0 - (elm.width()) / 2, "margin-top": 0 - (elm.height() / 2)});
});
}
});
$("img").middleify();
Fiddle
Update
Since setting a wider image width
100%
will cause a problem, let's make use of this logic on background:cover
$.fn.extend({
middleify: function(){
var i = $(this);
$.each(i, function(index, value) {
var elm = $(value);
var f = elm.parent();
var imgWidth = elm.width();
var imgHeight = elm.height();
var containerWidth = f.width();
var containerHeight = f.height();
var imgRatio = (imgHeight / imgWidth);
var containerRatio = (containerHeight / containerWidth);
if (containerRatio > imgRatio) {
var finalHeight = containerHeight;
var finalWidth = (containerHeight / imgRatio);
}
else {
var finalWidth = containerWidth;
var finalHeight = (containerWidth * imgRatio);
}
elm.css({position: "relative", "z-index": 2, width: finalWidth, height: finalHeight, top: "50%", left: "50%"});
elm.css({"margin-left": 0 - (elm.width()) / 2, "margin-top": 0 - (elm.height() / 2)});
});
}
});
$("img").middleify();
Fiddle