Reputation: 3
Is there a better way to do this as I use static numbers CodePen
var div = $('.fclass');
var par = $('.sclass');
const pos = par.position().top;
$(window).on('scroll',()=>{
if((par.position().top - pos) > -76){
div.removeClass('fixed');
}
if((par.position().top - pos) == 18){
div.addClass('fixed');
}
});
.fixed {
position: fixed;
top: 0;
}
.sticky {
position: -webkit-sticky;
/* Safari */
position: sticky;
top: 0;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="fclass fixed">
the first div
</div>
<div style="height: 1000px;"></div>
<p class="sclass sticky">
the second paragraph
</p>
<div style="height: 1000px;"></div>
Upvotes: 0
Views: 127
Reputation: 24001
I think there is no need for js scroll event at all .. good Html structure and css Sticky can do that for you
.paragraph{
height : 1000px;
}
.fixed {
position: fixed;
top: 0;
}
.sticky {
position: -webkit-sticky;
/* Safari */
position: sticky;
top: 0;
background : red;
color : #fff;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<!-- Paragraphs holds paragraphs -->
<div class="paragraphs">
<!-- First paragraph -->
<div class="paragraph">
<h1 class="paragraph-head sticky">First Paragraph</h1>
<div class="paragraph-content">
First paragraph content
</div>
</div>
<!-- Second paragraph -->
<div class="paragraph">
<h1 class="paragraph-head sticky">Second Paragraph</h1>
<div class="paragraph-content">
Second paragraph content
</div>
</div>
<!-- Third paragraph -->
<div class="paragraph">
<h1 class="paragraph-head sticky">Third Paragraph</h1>
<div class="paragraph-content">
Third paragraph content
</div>
</div>
</div>
Upvotes: 1