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');
}
Adam Bell
  • 1,049
  • 1
  • 16
  • 50
  • Does this answer your question? [Get url path and add class active on li](https://stackoverflow.com/questions/11772924/get-url-path-and-add-class-active-on-li) – Sridhar Nov 18 '22 at 05:45

1 Answers1

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>
samnoon
  • 1,340
  • 2
  • 13
  • 23