Shopify Code Help

I am not sure which language this code is so please forgive me, I think it’s javascript. Basically I have this code that a developer gave me:

<script>
    window.setTimeout(redirectCheckout, 2000);
    function redirectCheckout(){
  if(!(window.location.href.includes("?1"))){
    window.location.href = "https://www.example.com/checkout";
  }
    }
</script>

The code works but the only problem is it executes as soon as the page loads. I only want this code to load if

<span class="site-header__cart-indicator "></span>

is present within the code of the page.

So here is an example, I am using this theme on my shopify store:

If you check the html of the page you’ll see this code:

<span class="site-header__cart-indicator hide"></span>

What that means is that no one added anything to the cart, once someone adds something to the cart, that’s when you get:

<span class="site-header__cart-indicator "></span>

So, how can I modify the this code:

<script>
        window.setTimeout(redirectCheckout, 2000);
        function redirectCheckout(){
      if(!(window.location.href.includes("?1"))){
        window.location.href = "https://www.example.com/checkout";
      }
        }
    </script>

so that it executes only when
<span class="site-header__cart-indicator "></span>
is present?

You would need to check for two things. One, for the cart indicator, and two, to check that it’s not hidden.

function redirectCheckout() {
    ...
}
if (document.querySelector(".site-header__cart-indicator").length > 0 &&
    !document.querySelector(".site-header__cart-indicator").classList.contains("hide")) {
    window.setTimeout(redirectCheckout, 2000);
}

This code can be made easier to understand, by using a well-named function in the if condition.

function isVisible(className) {
    var el = document.querySelector(className);
    return (el.length > 0 && !el.classList.contains("hide"));
}
if (isVisible(".site-header__cart-indicator")) {
    window.setTimeout(redirectCheckout, 2000);
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.