jquery - Responsive resize content images -
i've got .content element on website contains main content. want able resize images when browser gets resized. i've made jquery function.
first setimgdata() function called. loops images , sets original size data-w , data-h attribute.
after resizeimg() called. based on original width , height image resized maximal content width (keeping aspect ratio).
the problem data-* attribute doesn't set. because $(this) inside load function doesn't point content image.
any ideas how can fix this?
function setimgdata(callback) { $(".content img").each( function() { var img = $(this); var pic_real_width, pic_real_height; $("<img/>") .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; pic_real_height = this.height; $(this).data("w", pic_real_width); $(this).data("h", pic_real_height); }); }); callback(); } function resizeimg() { var cwidth = $('.content').innerwidth(); var cpaddl = $('.content').css('padding-left').replace("px", ""); var cpaddr = $('.content').css('padding-right').replace("px", ""); var contentwidth = cwidth - cpaddl - cpaddr; $(".content img").each( function() { var imgw = $(this).data('w'); if( imgw > contentwidth ) { var imgh = $(this).data('h'); var newh = math.round( ( imgh * contentwidth ) / imgw ); $(this).width( contentwidth ).height( newh ); } }); }; $(function() { setimgdata(function () { resizeimg(); }); }); $(window).resize( function(){ resizeimg(); });
Comments
Post a Comment