Wednesday, 9 September 2020

Disable the Soldout variants in Shopify

Hello,

The following Solution will work for any number of options

Create "linked-options" snippet. add the following code in it

------------------------------- Code ------------------------

<script>

  // (c) Copyright 2016 Caroline Schnapp. All Rights Reserved. Contact: mllegeorgesand@gmail.com

  // See https://docs.shopify.com/themes/customization/navigation/link-product-options-in-menus

  var Shopify = Shopify || {};

  Shopify.optionsMap = {};

  Shopify.updateOptionsInSelector = function(selectorIndex) {


    switch (selectorIndex) {

      case 0:

        var key = 'root';

        var selector = jQuery('.single-option-selector:eq(0)');

        break;

      case 1:

        var key = jQuery('.single-option-selector:eq(0)').val();

        var selector = jQuery('.single-option-selector:eq(1)');

        break;

      case 2:

        var key = jQuery('.single-option-selector:eq(0)').val();  

        key += ' / ' + jQuery('.single-option-selector:eq(1)').val();

        var selector = jQuery('.single-option-selector:eq(2)');

    }


    var initialValue = selector.val();

    //   selector.empty();    

    var availableOptions = Shopify.optionsMap[key];

    for (var i=0; i<availableOptions.length; i++) {

      var option = availableOptions[i];

      console.log(option);

      var newOption = jQuery('<option></option>').val(option).html(option);

      //     selector.append(newOption);

      $(selector).find('option[value="'+option+'"]').addClass('available-variant');

      setTimeout(function(){ 

        $(selector).find('option').not( ".available-variant" ).attr('disabled','disabled').addClass('soldout-variant');

        setTimeout(function(){ 

          $('.soldout-variant').each(function(){

            var variantVal = $(this).text();

            if(variantVal.indexOf("Sold") <= 0){

              $(this).text(variantVal+" - Sold Out");

            }

          })

        },300);

      }, 200);

    }

    jQuery('.swatch[data-option-index="' + selectorIndex + '"] .swatch-element').each(function() {

      if (jQuery.inArray($(this).attr('data-value'), availableOptions) !== -1) {

        $(this).removeClass('soldout').show().find(':radio').removeAttr('disabled','disabled').removeAttr('checked');

      }

      else {

        $(this).addClass('soldout').hide().find(':radio').removeAttr('checked').attr('disabled','disabled');

      }

    });

    if (jQuery.inArray(initialValue, availableOptions) !== -1) {

      selector.val(initialValue);

    }

    selector.trigger('change');  


  };

  Shopify.linkOptionSelectors = function(product) {

    // Building our mapping object.

    for (var i=0; i<product.variants.length; i++) {

      var variant = product.variants[i];

      if (variant.available) {

        // Gathering values for the 1st drop-down.

        Shopify.optionsMap['root'] = Shopify.optionsMap['root'] || [];

        Shopify.optionsMap['root'].push(variant.option1);

        Shopify.optionsMap['root'] = jQuery.unique(Shopify.optionsMap['root']);

        // Gathering values for the 2nd drop-down.

        if (product.options.length > 1) {

          var key = variant.option1;

          Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];

          Shopify.optionsMap[key].push(variant.option2);

          Shopify.optionsMap[key] = jQuery.unique(Shopify.optionsMap[key]);

        }

        // Gathering values for the 3rd drop-down.

        if (product.options.length === 3) {

          var key = variant.option1 + ' / ' + variant.option2;

          Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];

          Shopify.optionsMap[key].push(variant.option3);

          Shopify.optionsMap[key] = jQuery.unique(Shopify.optionsMap[key]);

        }

      }

    }

    // Update options right away.

    Shopify.updateOptionsInSelector(0);

    if (product.options.length > 1) Shopify.updateOptionsInSelector(1);

    if (product.options.length === 3) Shopify.updateOptionsInSelector(2);

    // When there is an update in the first dropdown.

    jQuery(".single-option-selector:eq(0)").change(function() {

      Shopify.updateOptionsInSelector(1);

      if (product.options.length === 3) Shopify.updateOptionsInSelector(2);

      return true;

    });

    // When there is an update in the second dropdown.

    jQuery(".single-option-selector:eq(1)").change(function() {

      if (product.options.length === 3) Shopify.updateOptionsInSelector(2);

      return true;

    });  

  };


  {% if product.available and product.options.size > 1 %}

  var $addToCartForm = $('form[action="/cart/add"]');

  if (window.MutationObserver && $addToCartForm.length) {

    if (typeof observer === 'object' && typeof observer.disconnect === 'function') {

      observer.disconnect();

    }

    var config = { childList: true, subtree: true };

    var observer = new MutationObserver(function() {      

      Shopify.linkOptionSelectors({{ product | json }});

      observer.disconnect();

    });  

    observer.observe($addToCartForm[0], config);

  }

  {% endif %}


</script>


------------------------------------------------------

Add the following style in your CSS or Scss file

 .soldout-variant{

  background: #ebe9e9;

  }


------------------------------------------------------


Output:



Thanks



Monday, 31 August 2020

Append extra details in cart note (Shopify)

cart-template.liquid

replace note code by following as per theme (you must have basic knowledge of liquid coding)

  <section class="cart-note" style="{%- unless section.settings.show_notes -%}display: none;{%- endunless -%}">

    <textarea

              class="cart-note-content dummy-cart-note"

              placeholder="{{ section.settings.notes_placeholder }}"

              aria-label="{{ 'cart.notes' | t }}"></textarea>

  </section>


  <section class="cart-note" style="{%- unless section.settings.show_notes -%}display: none;{%- endunless -%}">

    <textarea

              class="cart-note-content"

              name="note"

              id="cart-note-content"

              placeholder="{{ section.settings.notes_placeholder | escape }}"

              aria-label="{{ 'cart.notes' | t }}" style="display: none;"  >{{ cart.note }}</textarea>

  </section>


Append following code where you want to show your extra options

   

    <div class="cart-donate-section">

      

      <div class="select-option-wrapper">

        <input type="checkbox" id="enabledonate" name="enabledonate" value="enabledonate" checked>

        <label for="enabledonate" class="show">

          I would like 10% of the profit to go as a donation to one of the organization from our list

        </label>

      </div>

      

      <div class="option-wrapper">

        <input type="radio" id="company1" name="company" value="organization1" checked>

        <label for="company1" class="show">organization1</label>

      </div>

      

      <div class="option-wrapper">  

        <input type="radio" id="company2" name="company" value="organization2">

        <label for="company2" class="show">organization2</label>

      </div>

      

    </div>

--------------------------------------------

Add Following css code in your css file

  .cart-donate-section label{

    display: inline-block !important;

    margin-left: 10px;

  }


  .cart-donate-section .option-wrapper {

    display: flex;

    align-items: center;

  }


  .cart-donate-section .select-option-wrapper {

    display: flex;

    align-items: baseline;

  }


  .cart-donate-section .option-wrapper.hide{

    display: none !important;

  }

  --------------------------------------------------------------

Add Following JS in your JS file

---------------------------------------------------------------


$('document').ready(function(){

  $('.dummy-cart-note').on('change',function(e){

    var customNote = $('.dummy-cart-note').val();

    $('#cart-note-content').val('');

    if($('#enabledonate').is(':checked')){

      $('.option-wrapper.hide').removeClass('hide');

      var selectedCompany = $('.cart-donate-section input[type="radio"]:checked').val();

      var appendHtmlContent = '';

      console.log(selectedCompany,'selectedCompany');

      appendHtmlContent = 'selectedCompany:"'+selectedCompany+'"';

      $('#cart-note-content').val(customNote + '  ' + appendHtmlContent);


    }

    else{

      $('.option-wrapper').addClass('hide');

      $('#cart-note-content').val(customNote);

      $('.option-wrapper input[type="radio"]:checked').prop('checked', false);

    }

  })

  

  $('#enabledonate').on('change',function(){

    

    var customNote = $('.dummy-cart-note').val();

    $('#cart-note-content').val('');


    if($('#enabledonate').is(':checked')){

      

      $('.option-wrapper.hide').removeClass('hide');

      $('.option-wrapper').eq(0).find('input[type="radio"]').prop('checked', true);

        

      var selectedCompany = $('.cart-donate-section input[type="radio"]:checked').val();

      var appendHtmlContent = '';

      console.log(selectedCompany,'selectedCompany');

      appendHtmlContent = 'selectedCompany:"'+selectedCompany+'"';

      $('#cart-note-content').val(customNote + '  ' + appendHtmlContent);

    }


    else{

      $('.option-wrapper').addClass('hide');

      $('#cart-note-content').val(customNote);

      $('.option-wrapper input[type="radio"]:checked').prop('checked', false);``

    }


  })


  $('.cart-donate-section input[type="radio"]').on('change',function(){

    var customNote = $('.dummy-cart-note').val();

    $('#cart-note-content').val('');


    if($('#enabledonate').is(':checked')){

      $('.option-wrapper.hide').removeClass('hide');

      var selectedCompany = $('.cart-donate-section input[type="radio"]:checked').val();

      var appendHtmlContent = '';

      console.log(selectedCompany,'selectedCompany');

      appendHtmlContent = 'selectedCompany:"'+selectedCompany+'"';

      $('#cart-note-content').val(customNote + '  ' + appendHtmlContent);

    }


    else{

      $('.option-wrapper').addClass('hide');

      $('#cart-note-content').val(customNote);

      $('.option-wrapper input[type="radio"]:checked').prop('checked', false);``

    }

  })

  

});

--------------------------------------------------

Output:

Geeky here

-----------------------------------------------------------------


Friday, 28 August 2020

How to turn automatic selection of variation off in Shopify? (done in themeL retina )

Open product-form.liquid

change "{% assign variant = product.selected_or_first_available_variant %}" to  "{% assign variant = product.selected_variant %}"

Add following code after the Add to cart button

<div class="select-an-option-block animated bounceIn hide">Pick a variant before adding to cart</div> 

Add Follwoing script at the end of product file

<script>

  var productOptions = [];

  {% for option in product.options %}

  var optionObj = {};

  optionObj[ {{ forloop.index0 }} ] = "{{ product.options[forloop.index0] }}";

  productOptions.push(optionObj);

  {% endfor %}

</script>

Add following code in to theme.js

  $(document).ready(function() {

    if( typeof(productOptions ) != "undefined" ){

      for(i=0;i<productOptions.length;i++) {

        const vowels = ['a', 'e', 'i', 'o', 'u'];

        let indef = 'a';

        const firstOptionLetter = productOptions[i][i][0].toLowerCase();

        if(vowels.includes(firstOptionLetter)) {

          indef = 'an';

        };

        $('.single-option-selector:eq('+ i +')')

        .filter(function() {

          return $(this).find('option').length > 1

        })

        .prepend(`<option value="">Pick an Option</option>`)

        .val('')

        .trigger('change');

        

        if($('.single-option-selector:eq('+ i +')').val() == ""){

          $('.purchase-details__buttons .action_button.add_to_cart').removeClass('disabled').removeAttr('disabled').addClass('select-option').text('Add To Cart');

          $('.modal_price').hide();

        }

        else{

          $('.purchase-details__buttons .action_button.add_to_cart').removeClass('select-option');

        }

      }

    }

    $('.select-option').on('click',function(){

      $('.select-an-option-block').removeClass('hide');

      $('.warning.animated.bounceIn').addClass('hide');

    })

  });


Attaching theme.js file

https://github.com/poojathakor/turn-automatic-selection-of-variation-off-in-Shopify/blob/master/theme.js


Thanks

Infinite scroll on collection page in Shopify

 Hello, Collection page structure is as followed {% paginate collection.products by 48 %} <div class="collection-content"> ...