views:

37

answers:

2

Hey Guys,

Having a bit of an issue please see the following code:

window.onload = function () {

    var imgHeight = $("#profile_img").height();

    var infoPanels = imgHeight - 6;
    //include borders and margin etc..
    var infoPanelsHeight = infoPanels / 4;
    $('.resize').css("height",infoPanelsHeight + "px"); 
    $('.resize2').css("height",infoPanelsHeight + "px");
}

What i’m trying to do is find the height of an image (floated:left), then divide it by 4 and use the outcome to set the height of 4 divs (floated:right), so they equal the height of the image in total.

I’m using this on a resizing project of mine but because the image height depends on the viewing window (in this case a mobile screen), the number is very rarely rounded up correctly so the divs are always out by 1-4 px.

So for a work around I want to find the height of the image, then if the height isn’t dividable by 4 adjust so it is... resize the image then resize the divs using the new image height.

So my question is how do i check the height of the image, if it isn’t dividable by 4 then make it so it is?

I’m using jquery and javascript generally.

Thanks for your help in advance.

Sam Tassell.

+1  A: 

You need the mod operator %:

imgHeight % 4

if the result is not '0' then you know imgHeight is not divisible by 4.

Dave Everitt
Thanks for the reply.Hmmm ok, but how do I then change the image size to be divisible by 4, like the closest number to which i could be divisible by 4.
Sam Tassell
if the result is not '0', subtract the result from the image height. If imageHeight is 103, imageHeight % 4 will give 3, so (given it will be safer to reduce rather than enlarge) you just need: newHeight -= imageHeight % 4; which will give you 100.
Dave Everitt
+2  A: 

I would try:

 if (imgHeight % 4 != 0) { // checks if the imgHeight is not dividable by 4
    $("#profile_img").attr("height") = Math.floor(imgHeight / 4) * 4; // set lowest height that is dividable by 4
 }

Note:

  • The image may become a little blurry because the result depends on your browser capabilities.
  • % is called modulus operator
MartyIX
Ok this looks close to what i need i'll give it a shot thanks =).
Sam Tassell
Hmm doesn't seem to be working only setting lowest height but not enabling it to be divisible by 4 :(
Sam Tassell
Opps my bad works a treat thanks!!
Sam Tassell