0

I have a specific product page within Shopify (although this could certainly apply to any URL with a variant selected by default in the URL query. I'd like it when this page loads, a class is immediately added to one of the div's upon load.

Basically, it's looking for a URL that contains this variant in the URL. So I suppose I could just shorten it to just ?variant=12345 instead. Maybe not?

I'm trying this jQuery script but it's just not working. What might be the proper solution here?

$(document).ready(function() {

var url = window.location.pathname;
if (url.indexOf('/products/my-product?variant=12345') !== -1) {
  $(".sales-widget").addClass('sales-on');
}
1

1 Answer 1

1

To take parameters in URI, you need to use both location.pathname and location.search as following:

var url = (window.location.pathname + window.location.search).substr(1);

See this example:

$(document).ready(function() {

  var url = (window.location.pathname + window.location.search).substr(1);
  if (url.indexOf('/products/my-product?variant=12345') !== -1) {
    $(".sales-widget").addClass('sales-on');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.