0

I want to check the height of an image (there are multiple such elements on a page). If the height is greater than 66px, I want to apply a negative top margin equal to half of its height.

The following code doesn't do anything. What is wrong with my if statement?

if($('.topstories a.image img').height() > 66){
    var margintop = -0.5 * ($(this).height() - 66);
    $(this).css('margin-top', 'margintop');
}

3 Answers 3

4

You've put the value to margintop in quotes, so it's treated as a string literal (an invalid value in this case). Try:

$(this).css('margin-top', margintop);
Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure you're applying the style to the correct element? What is this in this context? Have you tried specifying the selector in place of this? Something like $("#idOfImage").css('margin-top', margintop);
2

I don't know the rest of your function, but you to go through each image, you'll need to use a loop or each(). Something like:

$('.topstories a.image img').each(function(){
    if($(this).height() > 66)){
        var margintop = 0.5 * ($(this).height());
        $(this).css('margin-top', '-' + margintop);
    }
});

I'm thinking that your subtraction of 66 in the math operator also is causing an issue - if the image height is 67, and you subtract 66, you get 1. 1 * .5 sort of equals 0, so you wouldn't see an effect.

Comments

1

replace

$(this).css('margin-top', 'margintop');

with

$(this).css('margin-top', margintop);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.