Skip to content

Instantly share code, notes, and snippets.

@andrewlaskey
Created April 4, 2013 16:56
Show Gist options
  • Save andrewlaskey/5312055 to your computer and use it in GitHub Desktop.
Save andrewlaskey/5312055 to your computer and use it in GitHub Desktop.
Modified Backstretch.js to keep image aspect ratio constant when container dimensions change
<?php $imgdata = wp_get_attachment_image_src( get_post_thumbnail_id(), "full");
$imgurl = $imgdata[0]; // the url of the thumbnail picture
$imgwidth = $imgdata[1]; // thumbnail's width
$imgheight = $imgdata[2]; // thumbnail's height
if ($imgheight > 0) {
$ratio = $imgwidth / $imgheight;
} else {
$ratio = 1;
}
?>
<img src="<?php echo $imgurl; ?>" alt="" data-ratio="<?php echo $ratio; ?>">
/*modified backstretch.js*/
(function($){
//Adjust image size
$.fn.stretchnow = function() {
this.find('img').each( function() {
var bgCSS = { left: 0, top: 0 },
ratio = $(this).attr('data-ratio'),
parentWidth = $(this).parent().innerWidth(),
bgWidth = parentWidth,
parentHeight = $(this).parent().innerHeight(),
bgHeight = bgWidth / ratio,
bgOffset;
if ( bgHeight >= parentHeight ) {
bgOffset = (bgHeight - parentHeight) / 2;
bgCSS.top = '-' + bgOffset + 'px';
} else {
bgHeight = parentHeight;
bgWidth = bgHeight * ratio;
bgOffset = (bgWidth - parentWidth) / 2;
bgCSS.left = '-' + bgOffset + 'px';
}
$(this).css({ width: bgWidth, height: bgHeight }).css(bgCSS);
})
};
})(jQuery);
$(document).ready(function() {
$('.posts').stretchnow();
});
$(window).bind("resize", function() {
$('.posts').stretchnow();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment