I want to implement the selection of swatch options in a way that by default it should be selected 2nd swatch on listing pages.

Attribute name is color.

enter image description here

I looked over the following Blocks but not finding any clue.


Also, checked vendor\magento\module-swatches\view\frontend\web\js\swatch-renderer.js and found below code. But this does not work and in JS all other functions are start with underscore(_) not accessible.

if (firstSwatch.length) {

In some cases, Color and Size will be there but we want to select only 2nd position of color if have.

1 Answer 1


Detail information can be found in this link

To achieve this (2nd position), we can do by Override swatch-renderer.js in our theme Till Magento v2.3.3 - vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js

Magento v2.3.4 onwords - vendor/magento/module-swatches/view/base/web/js/swatch-renderer.js

Theme file location is - app/design/frontend/Vendor/Theme/Magento_Swatches/web/js/swatch-renderer.js

find _RenderControls() function update below code from // START - Custom code ... // End - Custom code at the end of this function : or follow below

_RenderControls: function () {
    var $widget = this,
        container = this.element,
        classes = this.options.classes,
        chooseText = this.options.jsonConfig.chooseText;
    $widget.optionsMap = {};
    // [... Existing code...]
    // Rewind options
    //Emulate click on all swatches from Request
    // START - Custom code
    if ($widget.inProductList) { // for product list page only 
        var defaultSelectCode = 'color',
            defaultPosition = 2,
            codeNotExistInFilter = true;
        $.each($.parseQuery(), $.proxy(function (attributeCode) {
            if(defaultSelectCode === attributeCode){
                codeNotExistInFilter = false;
        }, this));
        if(codeNotExistInFilter) {
            $widget.element.find('.' + this.options.classes.attributeClass +
                '[attribute-code="' + defaultSelectCode + '"]  [option-id]:nth-child('+defaultPosition+')').trigger('click');
    // End - Custom code

Note: defaultPosition = 1,2,3,... [any number position we can set]

above share detail done via overriding swatch-renderer.js in our theme but we can override this file in better way and update/add above shared code via js mixin - devdocs js_mixins - extend-jquery-widget - 'mage.SwatchRenderer'.

Please share any thought or input if need any further help/support on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.