Last active
June 22, 2022 16:56
-
-
Save tpage99/062ae842cb509bba88f9baaf93e1511b to your computer and use it in GitHub Desktop.
Pin add to cart button when not in view
This file contains 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
{% comment %} | |
Script to be included likely in product form snippet | |
Tried using intersection observer, and this may indeed be better, but issue with mobile and the button presenting too soon. Best solution at this time seems to be comparing scroll position and only showing when the offset is greater than the actual scroll position. | |
{% endcomment %} | |
<script> | |
const bodyRect = document.body.getBoundingClientRect(); | |
const btnRect = document.getElementById('atc-btn').getBoundingClientRect(); | |
const offset = btnRect.top - bodyRect.top; | |
window.addEventListener('scroll', showToATC, false); | |
function showToATC() { | |
let scrollPosition = 0; | |
scrollPosition = window.scrollY; | |
let div = document.getElementById('scroll-to-atc'); | |
scrollPosition < offset ? div.style.display = 'none' : div.style.display = "block"; | |
}; | |
</script> | |
{% comment %} | |
Snippet with simple styling | |
{% endcomment %} | |
<div id="scroll-to-atc"> | |
<a href="#product-form-{{ product.id }}">{% render 'icon-up-arrow' %}<span>Back to Add to Cart</span></a> | |
</div> | |
<style> | |
#scroll-to-atc { | |
position: fixed; | |
display: none; | |
bottom: 20px; | |
left: 45%; | |
background-color: {{ settings.button_cart_bg_color }}; | |
border-radius: 50px; | |
padding: 1rem 2rem; | |
animation: slide-in 1s 1; | |
z-index: 99; | |
} | |
@keyframes slide-in { | |
0% { | |
transform: translateY(100%); | |
; | |
} | |
50% { | |
transform: translateY(0%); | |
} | |
} | |
#scroll-to-atc a { | |
color: {{ settings.button_cart_text_color }}; | |
display: flex; | |
} | |
#scroll-to-atc:hover { | |
background-color: {{ settings.button_cart_bg_color--highlight }}; | |
} | |
#scroll-to-atc:hover a { | |
color: {{ settings.button_cart_text_color--highlight }}; | |
} | |
@media screen and (max-width: 767px) { | |
#scroll-to-atc { | |
bottom: 30px; | |
left: 42%; | |
padding: 1rem; | |
} | |
#scroll-to-atc a span { | |
display: none; | |
} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment