You have to copy the file swatch-renderer.js from
\vendor\magento\module-swatches\view\frontend\web\js
and put it in your theme folder like this:
app\design\frontend[THEME][THEME NAME]\Magento_Swatches\web\js\
and add few lines of code under the init function of this function line no. around 285
$.widget('mage.SwatchRenderer', {
so, the new init function should look like this. Note the custom code is inside the comment (custom script to select swatches automatically).
/**
* @private
*/
_init: function () {
if (_.isEmpty(this.options.jsonConfig.images)) {
this.options.useAjax = true;
// creates debounced variant of _LoadProductMedia()
// to use it in events handlers instead of _LoadProductMedia()
this._debouncedLoadProductMedia = _.debounce(this._LoadProductMedia.bind(this), 500);
}
if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
// store unsorted attributes
this.options.jsonConfig.mappedAttributes = _.clone(this.options.jsonConfig.attributes);
this._sortAttributes();
this._RenderControls();
//custom script to select swatches automatically
if($('body').hasClass('catalog-product-view')){
if (this.options.jsonConfig.attributes.length > 0) {
var selectswatch = this.element.find('.' + this.options.classes.attributeClass + ' .' + this.options.classes.attributeOptionsWrapper);
$.each(selectswatch, function (index, item) {
var swatchOption = $(item).find('div.swatch-option').first();
if (swatchOption.length && !$(item).find('div.swatch-option').hasClass('selected')) {
swatchOption.trigger('click');
}
});
}
var $selectedId = $('.color div.swatch-attribute-options').find('.selected').attr('id');
localStorage.setItem("selectedId", $selectedId);
}
// end of custom script
this._setPreSelectedGallery();
$(this.element).trigger('swatch.initialized');
} else {
console.log('SwatchRenderer: No input data received');
}
this.options.tierPriceTemplate = $(this.options.tierPriceTemplateSelector).html();
}
It's working for me. Please try this and let me know if it works for you. Sorry for the late reply. I am seeing this query now only.