Sticky cart icon for mobile

Recently I have implemented a sticky cart icon for mobile view of the website. It is an icon that comes into view when browsing shop categories. It only appears when scrolled down a certain length and if the cart is not empty. To do this I monitor the cart contents every time the user scrolls, or if the window resizes. You may notice that the way I check whether the website is in mobile view, is not by checking the screen size, which is unreliable. Instead I directly check whether the header changes its display property to display the mobile version. This is way more robust and flawless, as screen sizes can vary considerably as new devices enter the market.

HTML:

<div id="stickyCartMobile" class="stickyCartMobile"></div>
JAVASCRIPT:

document.addEventListener('DOMContentLoaded', function() {
const subString = 'shop';
const subStringTwo = 'shop/p/';
const getURL = window.location.href;
const content = document.querySelector(".content");
const stickyCartMobile = document.getElementById('stickyCartMobile');
const headerActions = document.querySelector('.header-actions');
const cartElement = document.querySelector('.sqs-cart-quantity');
var cartQuantity = cartElement.textContent;
let isTouch = false;
function checkHeader() {
const styles = window.getComputedStyle(headerActions);
isTouch = styles.getPropertyValue('display') !== 'flex';
}
checkHeader();
if (getURL.includes(subString) && !getURL.includes(subStringTwo)) {
content.appendChild(stickyCartMobile);
} else { 
stickyCartMobile.remove();
}
function showStickyCartMobile() {
stickyCartMobile.classList.add('showing');
}
function hideStickyCartMobile() {
stickyCartMobile.classList.remove('showing');
}
function checkScrollPos() {
if (window.scrollY >= 500 && isTouch && cartQuantity > 0) {
showStickyCartMobile();
} else {
hideStickyCartMobile();
	}
}
stickyCartMobile.addEventListener('click', function() {
window.location.href = '/cart';
});
function handleScrollResize() {
cartQuantity = cartElement.textContent;
checkScrollPos();
checkHeader();
}
window.addEventListener('scroll', handleScrollResize);
window.addEventListener('resize', handleScrollResize); 
handleScrollResize(); 
});
CSS:

#stickyCartMobile {
  width: 60px;
  height: 60px;
  position: fixed;
  top: 0px;
  right: -80px;
  display: block;
  background: url('https://images.squarespace-cdn.com/content/v1/6654b2fee26f292de13f1a9d/3538cab3-d423-445f-87f8-fe805c7b4ca4/mobileShopIcon3.png') no-repeat center center;
  background-size: contain;
  z-index: 999;
  cursor: pointer;
  pointer-events: auto;
  transition: all 1s ease;
  transform: scale(0.5);
}
#stickyCartMobile.showing {
  right: 9px;
  transform: scale(1);
}
Previous
Previous

Randomize items in shop

Next
Next

to-Bottom button