Skip to content

Instantly share code, notes, and snippets.

@gunjanpatel
Last active May 8, 2021 05:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunjanpatel/4982d312c28434b1ba2250b9d16f0b3e to your computer and use it in GitHub Desktop.
Save gunjanpatel/4982d312c28434b1ba2250b9d16f0b3e to your computer and use it in GitHub Desktop.
Sticky Add to cart button for product page Using Intersection Observer - This will show add to car button when native button will be disappear.
document.addEventListener("DOMContentLoaded", function () {
var productCartButton = document.querySelector('.product-cart'), stickyAddToCartButton = document.querySelector('.sticky-add-to-cart'), previousTop = 0;
if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) {
let productCartButtonObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
let addToCartButton = entry.target,
showstickyAddToCartButton = (entry.boundingClientRect.top < previousTop && entry.boundingClientRect.top < 0);
if (showstickyAddToCartButton) {
stickyAddToCartButton.classList.add('show');
} else {
stickyAddToCartButton.classList.remove('show');
}
// Set new top
previousTop = entry.boundingClientRect.top;
});
}, { threshold: 0.5});
productCartButtonObserver.observe(productCartButton);
}
});
@gunjanpatel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment