Search code examples
jquerycssscrolldetect

Detect When Div scrolls out of view


I have a div box with all the page content within it called .body-Container

and there is a div box that is placed on top of the .body-Container which is acting like a cover called .coverImg.

What I am trying to achieve is having the .body-Container positioned fixed until the .coverImg scrolls out of view, then changes position from fixed to relative. To allow the user to continue on viewing the content.

Then reverse, when scrolled to the top of the web page .body-Container becomes fixed and the .coverImg comes back into view.

I have given the .coverImg a magin-bottom:100vh which allows the div to scroll out of view.

I am having difficulty detecting when the bottom of the div hits the top of the window. To change the positioning.

Here is a jsfiddle to give a better understanding of what I am trying to do.

HTML:

<div class="coverImg" style="background-image:url(https://cdn.creativelive.com/fit/https%3A%2F%2Fcdn.creativelive.com%2Fagc%2Fcourses%2F5158-1.jpg/640);">
</div>

<div class="body-Container">
  <div class="content">
    <div class='section'>
    </div>
    <div class='section'>
    </div>
    <div class='section'>
    </div>
  </div>
</div>

CSS

.body-Container {
  position: relative;
  position:fixed;
  width: 100%;
  height: 99vh;
  margin: 0;
  padding: 0;
  border: 3px solid red;
}

.coverImg {
  width: 90%;
  height: 150vh;
  margin: 0 auto;
  border: 3px solid black;
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0;
  margin-bottom: 100vh;
  z-index: 2;
}

.content {
  width: 90%;
  height: 2500px;
  margin: 0 auto;
  position: absolute;
  top: 20px;
  bottom: 0px;
  left: 0px;
  right: 0;
  z-index: 1;
  background-color: skyblue;
}

Solution

  • Something along the lines of this may help. Each time the user scrolls, you're checking the position of the bottom of the div - if it's less than 0 (top of the window) you add the class outOfView (where you can add your position styling), if not, you remove the class:

        jQuery(window).on('scroll', function () {
            var top = jQuery(window).scrollTop(),
                divBottom = jQuery('.coverImg').offset().top + jQuery('.coverImg').outerHeight();
            if (divBottom > top) {
                jQuery('.coverImg').removeClass('outOfView');
            } else {
                jQuery('.coverImg').addClass('outOfView');
            }
        });