Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect When Div scrolls out of view [duplicate]

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;
}
like image 884
Jargonaut_ Avatar asked Oct 15 '25 14:10

Jargonaut_


1 Answers

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');
        }
    });
like image 92
nimaek Avatar answered Oct 18 '25 18:10

nimaek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!