I have this div called "sticky" within its parent "stickyTo", there are multiple parent divs, in my example I have only two and every scroll on that parent a sticky div comes out and will add a class on that div
var $sticky = jQuery('.sticky');
jQuery(window).on('scroll', function() {
var scroll = jQuery(window).scrollTop();
$sticky.each(function(){
const $this = jQuery(this);
const stickyTop = $this.offset().top;
const stickyBottom = stickyTop + $this.outerHeight();
const $stickyTo = $this.parent();
const stickyToTop = $stickyTo.offset().top;
const stickyToBottom = stickyToTop + $stickyTo.outerHeight();
if (stickyBottom >= stickyToBottom) {
if (scroll < stickyTop) {
//$sticky.addClass('fixed').removeClass('abs');
} else {
//$sticky.addClass('abs');
}
} else if (scroll > stickyToTop) {
$sticky.addClass('stuck');
} else if (scroll < stickyToTop) {
$sticky.removeClass('stuck');
}
})
});
Here is My FIDDLE so show you what I am trying to do
Problem with the current code is only trigerring the 2nd div, something wrong with my each() function
in jquery probably
In your each function, you should refer to the current element with $(this), not $sticky. https://jsfiddle.net/dyc19oxL/
jQuery(window).on('scroll', function() {
var scroll = jQuery(window).scrollTop();
$sticky.each(function(){
const $this = jQuery(this);
const stickyTop = $this.offset().top;
const stickyBottom = stickyTop + $this.outerHeight();
const $stickyTo = $this.parent();
const stickyToTop = $stickyTo.offset().top;
const stickyToBottom = stickyToTop + $stickyTo.outerHeight();
if (stickyBottom >= stickyToBottom) {
if (scroll < stickyTop) {
//$sticky.addClass('fixed').removeClass('abs');
} else {
//$sticky.addClass('abs');
}
} else if (scroll > stickyToTop) {
**$(this).addClass('stuck');**
} else if (scroll < stickyToTop) {
**$(this).removeClass('stuck');**
}
})