I’m trying to fetch variant id of product in Shopify and pass it to jQuery. But I’m unable to write script in (Sections/product-template.liquid).
Browser gives error of ‘Uncaught ReferenceError: jQuery is not defined’
I’ve written this code at the end of product-template.liquid.
<script>
jQuery(function($)
{
$current_variant_id = {{ product.selected_variant.id }};
$interval = setInterval(function()
{
if( $( '.product-single__thumbnail-item.slick-slide.slick-active.is-active' ).length > 0 )
{
if( !($( '.product-single__thumbnail-item[data-variant="'+$current_variant_id+'"]' ).hasClass('is-active')) )
{
$( '.product-single__thumbnail-item.slick-slide.slick-active.is-active' ).removeClass('is-active');
$( '.product-single__thumbnail-item[data-variant="'+$current_variant_id+'"]' ).addClass('is-active');
}
clearInterval( $interval );
}
},1);
});
</script>
What am I doing wrong here? Any guidance would be appreciated. Thanks!
2
Answers
The simple answer to this is for you to make sure your Javascript library is loaded in theme.liquid, in the head element. That ensures you can use your $ variable from that library.
It’s likely you are not using jQuery on your store website. The simplest way is edit your
theme.liquid
to include jQuery for every page. Just put ascript
tag below right before</head>
tag is ok:<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>