Aaron Prowse Aaron Prowse - 3 months ago 19
CSS Question

Jquery calculation with variables

Hi guys got a problem hopefully you can help,

var imageHeight = $("#slider > Img").height();
var imageFloat = (imageHeight + 31 / 2);

alert(imageFloat);

$("#slidernavright").css("marginTop",(imageFloat));


Can anyone see the issue here, the alert on
imageFloat
is bringing back a value of 15.5 which means the
imageHeight
is not being accounted for, The variable
imageHeight
is working and retrieving the correct number of the height image, also the margin is working and the
div
tag is being moved down by 15.5px. Dont know much about jQuery, I think this is just a syntax issue.

Answer

Most likely the img isn't fully loaded, so its height is 0.

To fix it, put an onload handler on the img. And also, check to see if it is cached using the .complete property, and of so, invoke the handler manually.

$("#slider > Img")
    .on("load", function() {
        var imageHeight = $(this).height();
        var imageFloat = (imageHeight + 31 / 2);

        alert(imageFloat);

        $("#slidernavright").css("marginTop",(imageFloat));
    })
    .filter(function() { return this.complete; })
    .trigger("load");

And keep in mind that / has higher precedence than +, so this:

var imageFloat = (imageHeight + 31 / 2);

is doing this:

var imageFloat = (imageHeight + (31 / 2));

instead of this:

var imageFloat = ((imageHeight + 31) / 2);