Created
March 4, 2014 10:56
-
-
Save kontur/9344293 to your computer and use it in GitHub Desktop.
jQuery make nested element (img / video) cover the container area with debounced resize listener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
var resizeTimer; | |
$(window).resize(function() { | |
clearTimeout(resizeTimer); | |
resizeTimer = setTimeout(onResize, 50); | |
}); | |
onResize(); | |
function onResize() { | |
var $container = $("#container"), | |
$content = $("#content"), | |
containerRatio = $container.width() / $container.height(), | |
contentRatio = $content.width() / $content.height() | |
if (containerRatio < contentRatio) { | |
$content.css({ | |
marginLeft: -($content.height() * contentRatio - $container.width()) / 2, | |
marginTop: "auto", | |
height: "100%", | |
width: "auto" | |
}); | |
} else { | |
$content.css({ | |
marginLeft: "auto", | |
marginTop: -($content.width() / contentRatio - $container.height()) / 2, | |
height: "auto", | |
width: "100%" | |
}); | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment