Barcode field contents on product pages - solution

5 0 3

So I needed to present the contents of the Barcode field right beside the Brand name field and after several tries I figured out the solution so someone looking to do the same can hopefully benefit from that.

Firstly, I'm not sure if anything I did is tied to the theme I'm using, but I guess it could be repurposed to suit any setup.

I had to modify two files: product-dropdown.js.liquid that contains the code triggered whenever a visitor chooses a different variant on the product page (like choosing a different size or color of a product) and product.liquid that was modified to contain some code activating in case a product contains no variants (i.e. there's no dropdown menu) and to include the field to contain the barcode text.

Inside product-dropdown.js.liquid there's a script beginning with

  //Triggered when an option is chosen
  var selectCallback = function(variant, selector) {

And you need to append the following piece of code right beneath the "var selectCallback ... {" line:

    if (variant.barcode !== '') {
      $("#barcodefield").html('Barcode: ' + variant.barcode);
    else {

The "else" clause exists to remove the "Barcode: " line from the page in case a particular variant doesn't contain any barcode information.

Moving on to product.liquid it was modified in two places. First you need to specifiy an element inside the page to contain the barcode information. I chose to place it near the brand name field but you can really put it anywhere:

<span id="barcodefield" style="margin-left: 10px"></span>

Second, a script should be placed somewhere inside the page, and I chose to put it right under the element described above that is triggered whenever your product contains no variants. The code from product-dropdown.js.liquid and your custom script in that file would never appear on such a page. So you need to inser the following into product.liquid:

 if( '{{product.variants.first.barcode}}' == '{{product.variants.last.barcode}}' ){
   $('#barcodefield').html('Barcode: {{ product.variants.first.barcode }}');

It's obvious that this merely compares if the barcodes are the same for your "first" and "last" product variants. Usually if there's only one variant (appearing as none) the condition will be true. It may also be true if you specify the same barcode for different variants. However it's quite benign because if there's more than one varian this script will be overridden by the first one.

Hope this helps somebody.

New Member
2 0 0

I need this but my theme does not have the product-dropdown.js.liquid . Any idea where I am supposed to add the first snippet of code?