Random Shop product embellishment
I added a creepy figure that appears on a random product in every shop category. Upon hovering over it, the figure slowly hides out of view behind the product image. It is a small embellishment I thought would be nice to have. I do not enable this feature on mobile. Below you will find code to select a random product, create the div, attach it and randomly set its horizontal position along the top of the product image. Then there is a hover event which in conjunction with the CSS makes the div slowly slide down and then removes it completely after a few seconds.
HTML:
JAVASCRIPT: <script> document.addEventListener('DOMContentLoaded', function () { const subString = 'shop'; const subStringTwo = 'shop/p/'; const getURL = window.location.href; if (getURL.includes(subString) && !getURL.includes(subStringTwo)) { // Mobile mode check const headerActions = document.querySelector('.header-actions'); let isTouch = false; function checkHeader() { const styles = window.getComputedStyle(headerActions); isTouch = styles.getPropertyValue('display') !== 'flex'; } checkHeader(); // Randomly pick a product const shopProducts = document.querySelectorAll('.grid-item'); if (shopProducts.length > 0 && isTouch == false) { const randomProduct = shopProducts[Math.floor(Math.random() * shopProducts.length)]; if (randomProduct) { // Attach the bee const productBeeDiv = document.createElement('div'); productBeeDiv.id = 'productBeeDiv'; productBeeDiv.classList.add('productBeeDiv'); randomProduct.appendChild(productBeeDiv); // Randomize position of bee const minMargin = 5; const maxMargin = 70; const randomMarginLeft = Math.floor(Math.random() * (maxMargin - minMargin + 1)) + minMargin; productBeeDiv.style.marginLeft = randomMarginLeft + '%'; //hide logic productBeeDiv.addEventListener('mouseover', function () { productBeeDiv.classList.add('hideAway'); setTimeout(function () { productBeeDiv.remove(); }, 4000); // ms before bee is removed }); } } } }); </script>
CSS: #productBeeDiv { width: 90px; height: 90px; position:absolute; z-index: -5; margin-top: -89px; background-image: url('https://images.squarespace-cdn.com/content/v1/6654b2fee26f292de13f1a9d/c98ffa06-eefc-4764-9fd3-2bae6cb9b22c/girlSilIcon1.png'); pointer-events: none; cursor: default; pointer-events: auto; background-repeat: no-repeat; background-position: center; background-size: contain; transition: all 2.3s ease-in-out; } #productBeeDiv.hideAway { transform: translateY(100px); }
The naming conventions with the word “bee” are a relic, initially I wanted a little bee sitting on product pages, but for now I opted for the creepy girl.
COMMENTS:
Leave a comment: