sinini
sinini

Reputation: 1433

jquery, margin-top depending of $(window).height()

i have a div-container and its top-margin should be set as a dependency of $(window).height(), so first i tried something like this:

        $("div#outerstart").css("margin-top",$(window).height() -805+"px");

it worked fine, but the margin-top should never be a negative, so i tried this:

        $("div#outerstart").css("margin-top",function () {
        if ($(window).height() < 805) {
            0+"px"  
        } else {
            $(window).height() -805+"px"
        }
    });

or also

 if ($(window).height() < $(document).height()) {...

but it shows no effect and margin-top is not set. do you have any suggestions?

Upvotes: 0

Views: 6295

Answers (2)

crishoj
crishoj

Reputation: 5927

A simpler solution would be to use Math.max instead of the anonymous function:

$("div#outerstart").css("margin-top", Math.max(0, $(window).height()-805)+"px");

Upvotes: 3

Marek Sebera
Marek Sebera

Reputation: 40661

let's change your code to use return keyword from function

$("div#outerstart").css("margin-top",function () {
    if ($(window).height() < 805) {
        return "0px";  
    } else {
        return ($(window).height() -805)+"px";
    }
});

Upvotes: 3

Related Questions