Jump to content

Set product/tag specific javascript

Go to solution Solved by tuanphan,

Recommended Posts

I've found a code injection for redirecting add to cart buttons that works well. My question: is it possible to set this to only run the javascript on certain products or certain product tags? 

Here's the script that I have:
https://www.primitusconsultancy.co.uk/blog/how-to-redirect-to-another-page-on-clicking-on-the-add-to-cart-button

<!-- REDIRECT ADD TO CART --->
<!-- REDIRECT ADD TO CART --->
<script>
function pcRedirectedPage() {
  let pcPageUrl = '/upload'; // The redirect page URL
  let pcAddToCartButton = document.querySelector('.sqs-add-to-cart-button');
  let pcProductVariants = document.querySelector('.product-variants');

  function pcVariantInStock() {
    return pcProductVariants.getAttribute('data-variant-in-stock');
  }

  function pcAddButtonClick() {
    if (pcProductVariants && pcVariantInStock() || !pcProductVariants) {
      setTimeout(function() {
        document.location.href = pcPageUrl;
      }, 1000);
    }
  }

  if (pcAddToCartButton) {
    pcAddToCartButton.addEventListener('click', pcAddButtonClick);
  }
}

document.addEventListener('DOMContentLoaded', pcRedirectedPage);
window.addEventListener('mercury:load', pcRedirectedPage);
</script>

 

Link to comment
  • Replies 1
  • Views 1.1k
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

  • Solution

You can add tag to these lines, suppose the tag name is: brand

let pcAddToCartButton = document.querySelector('.tag-brand .sqs-add-to-cart-button');
  let pcProductVariants = document.querySelector('.tag-brand .product-variants');

 

Email me if you have need any help (free, of course.). Answer within 24 hours. 
Or send to forum message

Contact Customer Care - Learn CSS - Buy me a coffee (thank you!)

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.