Last active
May 8, 2021 05:03
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://gist.github.com/gunjanpatel/6398339f60afdf66a6e73d37ce225445