Adam Bell
Adam Bell

Reputation: 1045

jQuery: Add Class on page load for specific URL path

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');
}

Upvotes: 0

Views: 30

Answers (1)

samnoon
samnoon

Reputation: 1743

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>

Upvotes: 1

Related Questions