Skip to content

Instantly share code, notes, and snippets.

@Bernix01
Created November 9, 2020 04:44
Show Gist options
  • Save Bernix01/39530ce63d7833467b7f4188dcf7aa4f to your computer and use it in GitHub Desktop.
Save Bernix01/39530ce63d7833467b7f4188dcf7aa4f to your computer and use it in GitHub Desktop.
Jquery to set an element to fixed while scrolling within its parent div and absolute position it to bottom when parent bottom reached.
(function ($) {
const fixme = $(".fixme");
// all JS code here
let fixmeTop = fixme.offset().top; // get initial position of the element
const parent1 = fixme.parent();
const parent2 = parent1.parent();
let fixmebottom =
parent2.position().top +
parent2.offset().top +
parent2.outerHeight(true) -
(fixme.height() + 64);
$(window).scroll(function () {
// assign scroll event listener
const currentScroll = $(window).scrollTop(); // get current position
const currentWidth = $(window).width();
const bottomLimit =
currentScroll + $(window).height() / 2 + fixme.outerHeight(true);
if (currentWidth > 798) {
if (currentScroll >= fixmeTop) {
if (bottomLimit <= fixmebottom) {
// within parent2
fixme.css({
position: "fixed",
top: "50%",
});
} else {
// below parent2
fixme.css({
position: "absolute",
top: `calc(100% - ${fixme.height() + 64}px)`,
});
}
} else {
// apply position: static
fixme.css({
// if you scroll above it
position: "absolute",
top: 0,
});
}
} else {
// apply position: aboslute
fixme.css({
// if you are on mobile
position: "relative",
top: 0,
});
}
});
$(window).resize(function () {
fixmeTop = fixme.offset().top; // get initial position of the element
fixmebottom =
parent2.position().top +
parent2.offset().top +
parent2.outerHeight(true) -
(fixme.height() + 64);
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment