Reputation: 3
I'm trying to figure out how to stop div from scrolling after reaching a certain point on a page, and for some reason I can't get it to work.
This is what it shows when I scroll all the way to the bottom of the footer, but I want it to stop after reaching the end of a section div
The div around the whole section is:
content
My jQuery:
jQuery(function($) {
var $el = $('#scroll'),
top = $el.offset().top;
$(window).scroll(function() {
var pos = $(window).scrollTop();
if (pos > top && !$el.hasClass('fixed')) {
$el.addClass('fixed');
} else if (pos < top && $el.hasClass('fixed')) {
$el.removeClass('fixed');
}
});
});
My CSS:
#scroll.fixed {
position: fixed;
top: 20%;
}
#scroll {
position: absolute;
top: 50px;
}
I tried
stopPosition = $('.content').offset().top;
But no luck.
Upvotes: 0
Views: 593
Reputation: 9738
In this example the scrolling will stop when you reach the div inside the .wrap you must get the position of that div and and set the window to that position each time you scroll down that div
$(document).ready(function() {
$(window).scroll(function() {
var stopScroll = $('.wrap > div:nth-child(2)').offset().top;
if ($(window).scrollTop() > $('.wrap div:nth-child(2)').offset().top) {
$(window).scrollTop(stopScroll); /*this will stop the scroll to not go further down*/
}
});
})
body {
font-family: 'Roboto', sans-serif;
font-size: 30px;
font-weight: 300;
margin-top: 0;
}
header {
width: 100%;
height: 50px;
line-height: 50px;
position: fixed;
font-size: 24px;
font-weight: 700;
color: #FFF;
padding: 12px 0;
margin: 0;
background: #252525;
transition: background 1s ease;
}
.wrap {
padding-top: 74px;
margin: 0;
}
.container {
width: 960px;
margin: 0 auto;
overflow: hidden;
}
.block-1,
.block-2 {
height: 500px;
text-align: center;
}
p {
margin-top: 185px;
}
.block-1 {
background: #27AACC;
color: #FFF;
}
.block-2 {
background: #668E99;
color: #FFF
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="block-1">
<div class="container">
</div>
</div>
<div class="block-2">
<div class="container">
</div>
</div>
<div class="block-1">
<div class="container">
</div>
</div>
</div>
Upvotes: 2