Saryk
Saryk

Reputation: 353

Expanding a div's height when page scrolls down

I'm looking for a way to dynamically change a div's height when a page scrolls. This is because I have a fixed panel on the right side of the screen, and a menu banner at the top.

When at the top of the page, the top of the side panel touches the bottom of the banner at the top. Thing is, when the page is scrolled down and the banner leaves the screen, this leaves a gap the size of the top banner between the top of the screen and the top of the side panel. I'd like to put a div between them that would grow in height when the page is scrolled down. Is there a way in css or js to do so ?

I can't just have the side panel have 100% height because it would hide some elements on the top banner, especially on lower resolution screens.

I added some ugly images made on paint to explain :

enter image description here enter image description here

This is the css for the side panel :

position: fixed;
right: 0;
top: 180px;
height:calc(100% - 180px);

Upvotes: 1

Views: 2442

Answers (3)

K Nugal
K Nugal

Reputation: 134

Hello I do not really understand your banner situation.. but regarding what you need, you can just call a js function whenever you scroll:

<body> 
<div class="content" onscroll="dynamicheight()">
</div>

<script>
function dynamicheight() {
    var content = document.getElementById("content");
    var y = content.scrollTop;
    document.getElementById('random').style.height = y;
}
</script>

This way the div with the id random will grow according to how much you scroll. Obviously you have to adjust it to your wishes. Hope this could guide you a bit.

Upvotes: 1

Ryan
Ryan

Reputation: 989

See first based on the content you can adjust it automatically.

How to make sidebar with same height as the content div?

Upvotes: 0

Saurabh Sonawane
Saurabh Sonawane

Reputation: 951

As per your question, you have to stick Panel to the top of viewport on scroll right?

For that purpose you can trick some negative margin equal to the height of menu bar like,

Check this fiddle here

$(window).scroll(function() {
    if ($(".sidepanel").offset().top > 50) {
        $(".sidepanel").addClass("stick-top");
    } else {
        $(".sidepanel").removeClass("stick-top");
    }
});
body{
  margin:0;
  padding:0;
  height:1000px
}
.menu{
  width:100%;
  height:50px;
  background:#111111
}
.sidepanel{
  width:200px;
  height:200px;
  background:#888888;
  position:fixed;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}

.sidepanel.stick-top{
  margin-top:-50px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>


<div class="menu"></div>
<div class="sidepanel"></div>

Upvotes: 0

Related Questions