I combined this jQuery function. The goal is to compute the fields of all the img elements inside the div.article , in order to balance the height of the image with the underlying document grid, which is 20 pixels. To fit my base grid, each image height must be a multiple of 20. If it is not, for example. one image height is 154 px, the function adds a 6 px marker to img, so that the balance with the base grid is restored.
The function works correctly , so my real question is :. Since I am not a programmer, I am interested in my code is very crappy, although it works, and if so, how can I improve the code?
JQuery Code:
$('div.article img').each(function() { // define line height of CSS baseline grid: var line_height = 20; // capture the height of the img: var img_height = $(this).attr('height'); // divide img height by line height and round up to get the next integer: var img_multiply = Math.ceil(img_height / line_height); // calculate the img margin needed to balance the height with the baseline grid: var img_margin = (img_multiply * line_height) - img_height; // if calculated margin < 5 px: if (img_margin < 5) { // then add another 20 px to avoid too small whitespace: img_margin = img_margin + 20; } // if img has caption: if ($($(this)).next().length) { // then apply margin to caption instead of img: $($(this)).next().attr('style', "margin-bottom: " + img_margin + "px;"); } else { // apply margin to img: $(this).attr('style', "margin-bottom: " + img_margin + "px;"); } });
Sample HTML code, img with title:
<div class="article"> <!-- [...] --> <p class="image"> <img src="http://example.com/images/123.jpg" width="230" height="154" alt="Image alt text goes here" /> <small>Image Caption Goes Here</small> </p> <!-- [...] --> </div>
Sample HTML code, img without a header:
<div class="article"> <!-- [...] --> <p class="image"> <img src="http://example.com/images/123.jpg" width="230" height="154" alt="Image alt text goes here" /> </p> <!-- [...] --> </div>
Edit: refined code based on Russ Cam's suggestions:
var line_height = 20; var min_margin = 5; $('div.article img').each(function() { var $this = $(this); // prefixed variable name with $ to remind it a jQuery object var img_height = $this.height(); var img_margin = ((Math.ceil(img_height / line_height)) * line_height) - img_height; img_margin = (img_margin < min_margin)? img_margin + line_height : img_margin; if ($this.next().length) { $this.next().css({'margin-bottom' : img_margin + 'px'}); } else { $this.css({'margin-bottom' : img_margin + 'px'}); } });
javascript jquery
univers
source share