Johann
Johann

Reputation: 691

Dynamic height() with window resize() with variable margin

So if have this function in order to dynamically set a div's height based on the browser height:

$(window).resize(function() {
    $('#slideshow').height($(window).height() - 110);
});

$(window).trigger('resize');

This works like a charm. As you can see, there's a 110px margin (that belongs to my header height).

This code is not optimal since, a header height might vary based on the current viewport.

Is there a way to set this up dynamically as well? Or at least set some conditions like:

If browser width is more than 768px then set a 110px margin. If less than 767, then the margin should be 80px.

This is my edited code so far, but I'm not sure if I'm on the right path:

$(window).resize(function() {

    var set_width = $(window).width();
    if(set_width <= 767) 

    $('#slideshow').height($(window).height() - 110);
});

$(window).trigger('resize');

Thanks a lot!

EDIT:


Now that I think of it better, this 110px are not a margin, it's a subtraction I'm doing in order for my header and the slideshow to fill the entire window. If I don't do this subtraction then I end up with my header height + slideshow height (which takes take browser height) making it scroll.

So I don't think I can do this with CSS. That's why I was thinking on a Javascript solution.

Upvotes: 1

Views: 3435

Answers (2)

ravish.hacker
ravish.hacker

Reputation: 1183

You can do something like this:

$(window).resize(function() {
    var buffer = ($(window).width()<768)?80:110;
    $('#slideshow').height($(window).height() - buffer );
});

$(window).trigger('resize');

As Halcyon suggested in comments, use css. That is the neatest way to do it.

Upvotes: 1

lshettyl
lshettyl

Reputation: 8171

So, you'd need something like the following. I hope the code is straightforward.

$(window).on("resize", function() {

    var winHeight = $(window).height();
    var headerHeight = $("header").height();
    $('#slideshow').height(winHeight - headerHeight);
});

$(window).trigger('resize');

The sample HTML I'd used as a model is:

<body>
    <header>my header</header>
    <div id="slideshow"></div>
</body>

Upvotes: 2

Related Questions