Tomer Lichtash
Tomer Lichtash

Reputation: 9262

How to hack an image height standard with jQuery?

I need a jQuery function to measure the height of an image, and add margin to the IMG element, so it will always result with a regular number that divides by 17 (which is my line-height).

Any help would be appreciated. Thanks.

UPDATE: I changed the title of the question and replaced PHP with jQuery. Coming to think about it, I need the function to run after the DOM is ready, on all images in a specific DIV. jQuery is more sensible than PHP in that case.

Upvotes: 0

Views: 191

Answers (5)

Adrian
Adrian

Reputation: 2923

If I understand your question correctly you want to know how to get each image height and add a margin as needed to get the height to a number evenly divisible by 17.

Here is a quick stab at the issue:

$(document).ready(function(){
       $('img').each(function() {
             var height = $(this).height;
             var modulus = height % 17;
             if(modulus != 0) {
                 var marginToAdd = 17 - modulus;
                 $(this).css("margin-bottom", marginToAdd); 
             }
       });
});

So what the above does is get each image on the page by it's tag. If you don't want every image on the page you might want to put all the images in a container so you have a more discriminating selector. Then it get the remainder from the division of the height by 17. If the remainder is 0 it does nothing if it is non-zero it figures out the margin that needs to be added to make it evenly divisible by 17 and adds it to the bottom of the image.

Upvotes: 2

Alfonso de la Osa
Alfonso de la Osa

Reputation: 1574

jQuery has some problems with document ready and image load on this issue.

if you want to check the image sizes you need to know if the image has been loaded or not because you can have the dom ready without the images loaded or the image will not trigger the onload event

so:

var image = $('#image');
if(image.get(0).complete){
    do_what_you_need();
} else {
    image.load(function(e){
        do_what_you_need();             
    });
}

Upvotes: 1

Mikk
Mikk

Reputation: 2229

You can get image height with jquery simply by doing

 $('#my_img_id').height();

For DOM ready, just check http://api.jquery.com/ready/

Edit: Is that what you were looking for?

<script>
$(function(){
    $('#myDiv img').each(function(){
        alert($(this).height()); 
    });
});

</script>
<div id="myDiv">
    <img src="asd.png">
    <img src="gg.png">
</div>

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 82048

$(this).children("img").attr("height")

There is a very similar question here: Using jQuery each to grab image height

Upvotes: 1

tanjir
tanjir

Reputation: 1334

You can use GD library: http://php.net/manual/en/function.getimagesize.php

Upvotes: 0

Related Questions