background image
Eric's picture

I'm working on a piece of code that outputs a variable number of node fields into a table that has one row. I decided to use a table and tds to solve the following: 1) maintaining a true MVC by keeping my CSS (view) separate from my code (model); and 2) implement a variable number column solution that does not require a hard-coded width. Anyway... After implementing the table, I realized large images in my content would skew the overall width of each td. I decided to write some jQuery to resize images in my content automatically. This code figures out the overall width of my page (parent div of the table) and the padding on each td, and adjusts as necessary...

<?php
$(document).ready(function(){
   
 
// get width of main column
 
var mainWidth = $('#MYPARENTDIV').innerWidth();

 
// get number of columns
 
tdCount = $('td', 'table.MYTABLECLASS tr').length;
   
 
// tally td padding
 
var tdPadding = 0;
  $(
'td', 'table.MYTABLECLASS tr').each(function(){
   
tdPadding += $(this).innerWidth() - $(this).width();
  });
   
 
// calculate new max image width
 
var maxWidth = (mainWidth - tdPadding) / tdCount;
   
 
// adjust image dimensions
 
$('img', 'table.MYTABLECLASS tr td').each(function(i){
   
// check the width of the image
   
if ($(this).width() > maxWidth) {
     
// calculate new image dimensions
     
newWidth = maxWidth;
     
newHeight = $(this).height() / ( $(this).width() / maxWidth );
           
     
// set new image dimensions
     
$(this).height(newHeight).width(newWidth);
    }
  });   
});
?>

Image Resize

Eric;

Thank you for sharing this code snippet. It's a really big help in managing UGC content that has unpredictable size dimensions.

Cheers,

Rusty

Eric's picture

sweet

Glad to help, cheers! -Eric