Friday, January 9, 2026
  • Home
  • About Us
  • Disclaimer
  • Contact Us
  • Terms & Conditions
  • Privacy Policy
T3llam
  • Home
  • App
  • Mobile
    • IOS
  • Gaming
  • Computing
  • Tech
  • Services & Software
  • Home entertainment
No Result
View All Result
  • Home
  • App
  • Mobile
    • IOS
  • Gaming
  • Computing
  • Tech
  • Services & Software
  • Home entertainment
No Result
View All Result
T3llam
No Result
View All Result
Home Services & Software

Magento 2 Customized Content material in Configurable Product Media Gallery

admin by admin
November 20, 2023
in Services & Software
0
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter


Hi there Buddies, on this weblog, we are going to find out how can we add further or customized content material or media to Configurable Merchandise’ Fotorama media gallery on the entrance finish in visible and textual content swatches case.

For dropdown swatch sort, examine our weblog Add Customized Content material in Configurable Product Media Gallery – Magento 2

In Magento 2, on the configurable product web page, for rendering the swatch attributes, <magento-root-dir.>/vendor/magento/module-swatches/view/base/internet/js/swatch-renderer.js file is accountable.

So, so as to add further content material within the configurable product’s media gallery(in textual content and visible swatch case), we have to override a number of strategies of the swatch-renderer js file.
For instance, updateBaseImage, _onGalleryLoaded and _loadMedia features are liable for updating the media gallery after swatch rendering and swatch choice.

So, so as to add the customized content material I’ve overridden the required features and added some required recordsdata that are required to attain our purpose.
To begin with, we are going to create a demo module. Right here, I’ve created the Webkul_ExtraContentInFotorama module. Additional, comply with the beneath steps:

1. Create a di.xml file contained in the <magento-root-dir>/app/code/Webkul/ExtraContentInFotorama/and many others/ listing.

<?xml model="1.0"?>
<!--
/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/and many others/config.xsd">
  <!--Add Additional Configuration Knowledge In JsonConfig-->
  <sort identify="MagentoConfigurableProductBlockProductViewTypeConfigurable">
    <plugin identify="Wk_afterGetJsonConfig"
      sort="WebkulExtraContentInFotoramaPluginConfigurableProductBlockConfigurableAfterGetJsonConfigPlugin"
      sortOrder="50" />
	</sort>
</config>

2. Create ConfigurableAfterGetJsonConfigPlugin.php file contained in the <magento-root-dir>/app/code/Webkul/ExtraContentInFotorama/Plugin/ConfigurableProduct/Block/ listing.

<?php
/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
namespace WebkulExtraContentInFotoramaPluginConfigurableProductBlock;

class ConfigurableAfterGetJsonConfigPlugin
{
    /**
     * @var MagentoFrameworkAppRequestInterface
     */
    protected $request;

    /**
     * @var MagentoFrameworkJsonHelperData
     */
    protected $jsonHelper;

    /**
     * Initialize dependencies
     *
     * @param MagentoFrameworkJsonHelperData $jsonHelper
     * @param MagentoFrameworkAppRequestInterface $request
     * @return void
     */
    public operate __construct(
        MagentoFrameworkJsonHelperData $jsonHelper,
        MagentoFrameworkAppRequestInterface $request
    ) {
        $this->request    = $request;
        $this->jsonHelper = $jsonHelper;
    }

    /**
     * Composes configuration for js
     *
     * @param MagentoConfigurableProductBlockProductViewTypeConfigurable $topic
     * @param string $resultJson
     * @return string
     */
    public operate afterGetJsonConfig(
        MagentoConfigurableProductBlockProductViewTypeConfigurable $topic,
        $resultJson
    ) {
        //Verify if request is created from product web page//
        if (strtolower($this->request->getFullActionName()) == "catalog_product_view") {
            $outcome = $this->jsonHelper->jsonDecode($resultJson);

            /////Set Additional Configuration Knowledge/////
            $customConfig = [];
            
            $customConfig["linkUrl"] = "https://webkul.com/weblog/design-patterns-in-magento-2/";
            $customConfig["thumbnailImage"] = "Present a thumbnail Picture URL";
            $customConfig["linkContent"] =  "Design Patterns in Magento 2";

            //set tremendous attribute id, on which choice you need to change the content material//
            $customConfig["defaultVariantAttribute"] = 138; 

            $outcome["customConfig"] = $customConfig;

            $resultJson = $this->jsonHelper->jsonEncode($outcome);

            /////////
        }
       
        return $resultJson;
    }
}

3. Create a requires-config.js file to say the mixin file for the swatch-renderer.js file contained in the <magento-root-dir.>/app/code/Webkul/ExtraContentInFotorama/view/frontend/ listing.

/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
var config = {
    config: {
        mixins: {
            'Magento_Swatches/js/swatch-renderer' : {'Webkul_ExtraContentInFotorama/js/swatch-renderer':true}
        }
    }
};

4. Create a swatch-renderer.js file contained in the <magento-root-dir.>/app/code/Webkul/ExtraContentInFotorama/view/frontend/internet/js/ listing.

/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
outline([
    'jquery',
    'underscore',
    'mage/translate'
], operate ($, _, $t) {
    'use strict';

    return operate (SwatchRenderer) {
        
        $.widget('mage.SwatchRenderer', SwatchRenderer, {
            /**
             * Replace [gallery-placeholder] or [product-image-photo]
             * @param {Array} photos
             * @param {jQuery} context
             * @param {Boolean} isInProductView
             */
            updateBaseImage: operate (photos, context, isInProductView) {
                var self = this.choices.jsonConfig.customConfig; //Load Customized Content material Config.

                ///Verify if linkUrl is empty//
                if (self.linkUrl == "" || self.linkUrl == null) {
                    return this._super(photos, context, isInProductView);
                }
                /////

                var justAnImage = photos[0],
                    initialImages = this.choices.mediaGalleryInitial,
                    imagesToUpdate,
                    gallery = context.discover(this.choices.mediaGallerySelector).knowledge('gallery'),
                    isInitial;

                if (isInProductView) {
                    if (_.isUndefined(gallery)) {
                        context.discover(this.choices.mediaGallerySelector).on('gallery:loaded', operate () {
                            this.updateBaseImage(photos, context, isInProductView);
                        }.bind(this));

                        return;
                    }

                    imagesToUpdate = photos.size ? this._setImageType($.lengthen(true, [], photos)) : [];
                    isInitial = _.isEqual(imagesToUpdate, initialImages);

                    if (this.choices.gallerySwitchStrategy === 'prepend' && !isInitial) {
                        //Take away Further Additional Content material
                        initialImages = this._removeExtraContentfromArray(initialImages);
                        //////////////
                        imagesToUpdate = imagesToUpdate.concat(initialImages);
                    }

                    imagesToUpdate = this._setImageIndex(imagesToUpdate);

                    gallery.updateData(imagesToUpdate);
                    this._addFotoramaVideoEvents(isInitial);
                } else if (justAnImage && justAnImage.img) {
                    context.discover('.product-image-photo').attr('src', justAnImage.img);
                }
            },

            /**
             * Callback which fired after gallery will get initialized.
             *
             * @param {HTMLElement} factor - DOM factor related to a gallery.
             */
            _onGalleryLoaded: operate (factor) {
                var galleryObject = factor.knowledge('gallery');

                ////////////
                var currImgs = galleryObject.returnCurrentImages();
            
                //Load Additional Content material//
                this._loadExtraContent();

                //Push Additional Content material in photos gallery
                var self = this.choices.jsonConfig.customConfig;
                var modelThumbnailImg = self.thumbnailImage;
                
                this._pushExtraContent(currImgs, modelThumbnailImg);
                //////////////////

                this.choices.mediaGalleryInitial = currImgs;

                ///Replace Present Photographs in Media Gallery///
                galleryObject.updateData(currImgs);
            },

            /**
             * Load media gallery utilizing ajax or json config.
             *
             * @personal
             */
            _loadMedia: operate () {
                var self = this.choices.jsonConfig.customConfig; //Get Customized Config.

                var $predominant = this.inProductList ?
                        this.factor.dad and mom('.product-item-info') :
                        this.factor.dad and mom('.column.predominant'),
                    photos;

                if (this.choices.useAjax) {
                    this._debouncedLoadProductMedia();
                }  else {
                    photos = this.choices.jsonConfig.photos[this.getProduct()];

                    if (!photos) {
                        photos = this.choices.mediaGalleryInitial;
                    }

                    ////////////Load Additional Content material/////
                    this._loadExtraContent();
                    //Take away Additional Content material from picture array
                    photos = this._removeExtraContentfromArray(photos);

                    var self = this.choices.jsonConfig.customConfig;
                    var modelThumbnailImg = self.thumbnailImage;
                    
                    //Push Additional Content material from picture array
                    this._pushExtraContent(photos, modelThumbnailImg);
                    //////////////////
            
                    this.updateBaseImage(this._sortImages(photos), $predominant, !this.inProductList);
                }
            },


            /**
             * Delete Further Additional Content material from array
             * 
             * @param {Array} imagesArray
             * @returns {Array}
             * @personal
             */
            _removeExtraContentfromArray: operate(imagesArray) {
                imagesArray = imagesArray.filter(factor => factor.sort !== "ExtraContent");
                return imagesArray;
            },

            /**
             * Push Additional Content material in array
             * 
             * @param {Array} fotoramaContentArray
             * @param {string} modelThumbnailImg
             * @personal
             */
            _pushExtraContent: operate(fotoramaContentArray, modelThumbnailImg) {
                var self = this.choices.jsonConfig.customConfig;

                if (typeof fotoramaContentArray != "undefined" && 
                    (self.linkUrl != "" || self.linkUrl != null)) {
                        fotoramaContentArray.unshift({
                        thumb: modelThumbnailImg,
                        src: self.linkUrl,
                        sort: 'ExtraContent',
                        caption: self.linkContent,
                        isMain: "true",
                        place: 0
                    });
                }
            },

            /**
             * Get Chosen Variant Worth
             * 
             * @return {string}
             * @personal
             */
            _getSelectedVariantValue: operate() {
                var self = this.choices.jsonConfig.customConfig;
                var optionTextVal = "";
                var optionTextArr = []; 
                var selectedText = "";
                var selectedVal = "";
                var selectedSwatchAttrId = 0;
                var defaultVariantAttribute = self.defaultVariantAttribute;
            
                if ($('.product-options-wrapper choose[id^="attribute"]').discover().size) {
                    selectedText = $('.product-options-wrapper choose[id^="attribute"] choice:chosen').textual content();
                } else {
                    if ($('.swatch-attribute-options .swatch-option[aria-checked="true"]').size) {
                        var swatchId = "";
                        var idParts = [];
                        $('.swatch-attribute-options .swatch-option[aria-checked="true"]').every(operate() {
                            swatchId = $(this).attr("id");
                            idParts = swatchId.cut up('-');

                            for (let index=0; index<idParts.size; index++) {
                                if ($.isNumeric(idParts[index])) {
                                    selectedSwatchAttrId = idParts[index];
                                    break;
                                }
                            }
                            if (parseInt(defaultVariantAttribute) == selectedSwatchAttrId) {
                                selectedText = $(this).attr("data-option-label");
                            }
                        });
                    }
                }

                /////Get Chosen Variant Worth/////
                selectedVal = $('.product-options-wrapper choose[id^="attribute"] choice:chosen').val();
                if (selectedVal == "" && $('.product-options-wrapper choose[id^="attribute"]').discover().size) {
                    selectedText = $('.product-options-wrapper choose[id^="attribute"] choice:eq(1)').textual content();
                } else {
                    selectedVal = selectedText;
                }
                /////

                if ($('.product-options-wrapper choose[id^="attribute"]').discover().size) {
                    if (selectedText.indexOf('+') == -1) {
                        optionTextVal = selectedText;
                    } else {
                        optionTextArr =  selectedText.cut up('+');
                        optionTextVal = $.trim(optionTextArr[0]);
                    }    
                } else {
                    optionTextVal = selectedVal;
                }
              
                return optionTextVal;
            },


            /**
             * Occasion for swatch choices
             *
             * @param {Object} $this
             * @param {Object} $widget
             * @personal
             */
            _OnClick: operate ($this, $widget) {
                var self = this.choices.jsonConfig.customConfig;
                var wkExtraContentDiv = $("#wkExtraContent");
                var mainVariantAttributeId = self.defaultVariantAttribute;

                var swatchId = $this.attr("id");
                var idParts = swatchId.cut up('-');
                var selectedSwatchAttrId = 0;

                for (let index=0; index<idParts.size; index++) {
                    if ($.isNumeric(idParts[index])) {
                        selectedSwatchAttrId = idParts[index];
                        break;
                    }
                }
                
                if (typeof wkExtraContentDiv == "object" 
                    && selectedSwatchAttrId == parseInt(mainVariantAttributeId)) {
                        var label = $this.attr("data-option-label");
                        var bgColor = "#86FA50";

                        change (label) {
                            case 'Gold': bgColor = "#DFD906"; break;
                            case 'Diamond': bgColor = "#AFF3F2"; break;
                        }

                        setTimeout(operate(){
                            $("#wkExtraContent").css("background-color", bgColor);
                        }, 300);
                        
                }

                this._super($this, $widget);
            },

            /**
             * Load Additional Content material
             * 
             * @personal
             */
            _loadExtraContent: operate() {
                var thisJs = this;
                var self = this.choices.jsonConfig.customConfig;
                var divFotorama = $('div.gallery-placeholder > div.fotorama');

                if (self.linkUrl == "") {
                    return;
                }
                var variantText = "None";
                 
                //Get Chosen Variant Worth
                variantText = thisJs._getSelectedVariantValue();

                divFotorama.on('fotorama:load', operate fotorama_onLoad(e, fotorama, further) {

                    if (further.body.sort === 'ExtraContent' && further.body.src != "") {
                        var extraContentHtml = '';
                       
                        extraContentHtml += '<div id="wkExtraContent" type="background-color:#86FA50">';
                        extraContentHtml += '<h1 type="margin-top:250px">'+'Additional Content material'+'</h1>';
                        ///Present Variant Textual content///
                        if (variantText != '') {
                            extraContentHtml += '<p type="font-size:20px">Chosen Variant:</p>';
                            extraContentHtml += '<p type="font-size:18px">'+variantText+'</p><br/>';
                        }
                        /////////////////
                        extraContentHtml += '<a href="'+self.linkUrl+'" type="font-size:18px">'
                        extraContentHtml += self.linkContent+'</a>';
                        extraContentHtml += '</div>';

                        further.body.$stageFrame.html(extraContentHtml);
                    }
                });
            }

        });

        return $.mage.SwatchRenderer;
    };
});

5. After including the above code to your module. Deploy the code and see the outcome within the textual content swatch case. Check with the beneath photos for the outcome.

TextSwatchAttribute
TextSwatchResult

6. See the outcome within the visible swatch case. Check with the beneath photos for the outcome.

VisualSwatchAttribute
VisualSwatchResult

Observe: Keep in mind so as to add <sequence> within the module.xml file to load the Magento_Swatches module earlier than your customized module.

You might also examine the Magento 2 Superior Media Supervisor extension to edit the pictures current within the media gallery and add watermarks, filter, rotate, resize, and extra.

author-thumb


Khushboo Sahu
8 Badges

20 November 2023

RelatedPosts

The state of strategic portfolio administration

The state of strategic portfolio administration

June 11, 2025
You should utilize PSVR 2 controllers together with your Apple Imaginative and prescient Professional – however you’ll want to purchase a PSVR 2 headset as properly

You should utilize PSVR 2 controllers together with your Apple Imaginative and prescient Professional – however you’ll want to purchase a PSVR 2 headset as properly

June 11, 2025
Consumer Information For Magento 2 Market Limit Vendor Product

Consumer Information For Magento 2 Market Limit Vendor Product

June 11, 2025


Hi there Buddies, on this weblog, we are going to find out how can we add further or customized content material or media to Configurable Merchandise’ Fotorama media gallery on the entrance finish in visible and textual content swatches case.

For dropdown swatch sort, examine our weblog Add Customized Content material in Configurable Product Media Gallery – Magento 2

In Magento 2, on the configurable product web page, for rendering the swatch attributes, <magento-root-dir.>/vendor/magento/module-swatches/view/base/internet/js/swatch-renderer.js file is accountable.

So, so as to add further content material within the configurable product’s media gallery(in textual content and visible swatch case), we have to override a number of strategies of the swatch-renderer js file.
For instance, updateBaseImage, _onGalleryLoaded and _loadMedia features are liable for updating the media gallery after swatch rendering and swatch choice.

So, so as to add the customized content material I’ve overridden the required features and added some required recordsdata that are required to attain our purpose.
To begin with, we are going to create a demo module. Right here, I’ve created the Webkul_ExtraContentInFotorama module. Additional, comply with the beneath steps:

1. Create a di.xml file contained in the <magento-root-dir>/app/code/Webkul/ExtraContentInFotorama/and many others/ listing.

<?xml model="1.0"?>
<!--
/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/and many others/config.xsd">
  <!--Add Additional Configuration Knowledge In JsonConfig-->
  <sort identify="MagentoConfigurableProductBlockProductViewTypeConfigurable">
    <plugin identify="Wk_afterGetJsonConfig"
      sort="WebkulExtraContentInFotoramaPluginConfigurableProductBlockConfigurableAfterGetJsonConfigPlugin"
      sortOrder="50" />
	</sort>
</config>

2. Create ConfigurableAfterGetJsonConfigPlugin.php file contained in the <magento-root-dir>/app/code/Webkul/ExtraContentInFotorama/Plugin/ConfigurableProduct/Block/ listing.

<?php
/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
namespace WebkulExtraContentInFotoramaPluginConfigurableProductBlock;

class ConfigurableAfterGetJsonConfigPlugin
{
    /**
     * @var MagentoFrameworkAppRequestInterface
     */
    protected $request;

    /**
     * @var MagentoFrameworkJsonHelperData
     */
    protected $jsonHelper;

    /**
     * Initialize dependencies
     *
     * @param MagentoFrameworkJsonHelperData $jsonHelper
     * @param MagentoFrameworkAppRequestInterface $request
     * @return void
     */
    public operate __construct(
        MagentoFrameworkJsonHelperData $jsonHelper,
        MagentoFrameworkAppRequestInterface $request
    ) {
        $this->request    = $request;
        $this->jsonHelper = $jsonHelper;
    }

    /**
     * Composes configuration for js
     *
     * @param MagentoConfigurableProductBlockProductViewTypeConfigurable $topic
     * @param string $resultJson
     * @return string
     */
    public operate afterGetJsonConfig(
        MagentoConfigurableProductBlockProductViewTypeConfigurable $topic,
        $resultJson
    ) {
        //Verify if request is created from product web page//
        if (strtolower($this->request->getFullActionName()) == "catalog_product_view") {
            $outcome = $this->jsonHelper->jsonDecode($resultJson);

            /////Set Additional Configuration Knowledge/////
            $customConfig = [];
            
            $customConfig["linkUrl"] = "https://webkul.com/weblog/design-patterns-in-magento-2/";
            $customConfig["thumbnailImage"] = "Present a thumbnail Picture URL";
            $customConfig["linkContent"] =  "Design Patterns in Magento 2";

            //set tremendous attribute id, on which choice you need to change the content material//
            $customConfig["defaultVariantAttribute"] = 138; 

            $outcome["customConfig"] = $customConfig;

            $resultJson = $this->jsonHelper->jsonEncode($outcome);

            /////////
        }
       
        return $resultJson;
    }
}

3. Create a requires-config.js file to say the mixin file for the swatch-renderer.js file contained in the <magento-root-dir.>/app/code/Webkul/ExtraContentInFotorama/view/frontend/ listing.

/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
var config = {
    config: {
        mixins: {
            'Magento_Swatches/js/swatch-renderer' : {'Webkul_ExtraContentInFotorama/js/swatch-renderer':true}
        }
    }
};

4. Create a swatch-renderer.js file contained in the <magento-root-dir.>/app/code/Webkul/ExtraContentInFotorama/view/frontend/internet/js/ listing.

/**
 * Webkul Software program.
 *
 * @class  Webkul
 * @package deal   Webkul_ExtraContentInFotorama
 * @creator    Webkul Software program Personal Restricted
 * @copyright Webkul Software program Personal Restricted (https://webkul.com)
 * @license   https://retailer.webkul.com/license.html
 */
outline([
    'jquery',
    'underscore',
    'mage/translate'
], operate ($, _, $t) {
    'use strict';

    return operate (SwatchRenderer) {
        
        $.widget('mage.SwatchRenderer', SwatchRenderer, {
            /**
             * Replace [gallery-placeholder] or [product-image-photo]
             * @param {Array} photos
             * @param {jQuery} context
             * @param {Boolean} isInProductView
             */
            updateBaseImage: operate (photos, context, isInProductView) {
                var self = this.choices.jsonConfig.customConfig; //Load Customized Content material Config.

                ///Verify if linkUrl is empty//
                if (self.linkUrl == "" || self.linkUrl == null) {
                    return this._super(photos, context, isInProductView);
                }
                /////

                var justAnImage = photos[0],
                    initialImages = this.choices.mediaGalleryInitial,
                    imagesToUpdate,
                    gallery = context.discover(this.choices.mediaGallerySelector).knowledge('gallery'),
                    isInitial;

                if (isInProductView) {
                    if (_.isUndefined(gallery)) {
                        context.discover(this.choices.mediaGallerySelector).on('gallery:loaded', operate () {
                            this.updateBaseImage(photos, context, isInProductView);
                        }.bind(this));

                        return;
                    }

                    imagesToUpdate = photos.size ? this._setImageType($.lengthen(true, [], photos)) : [];
                    isInitial = _.isEqual(imagesToUpdate, initialImages);

                    if (this.choices.gallerySwitchStrategy === 'prepend' && !isInitial) {
                        //Take away Further Additional Content material
                        initialImages = this._removeExtraContentfromArray(initialImages);
                        //////////////
                        imagesToUpdate = imagesToUpdate.concat(initialImages);
                    }

                    imagesToUpdate = this._setImageIndex(imagesToUpdate);

                    gallery.updateData(imagesToUpdate);
                    this._addFotoramaVideoEvents(isInitial);
                } else if (justAnImage && justAnImage.img) {
                    context.discover('.product-image-photo').attr('src', justAnImage.img);
                }
            },

            /**
             * Callback which fired after gallery will get initialized.
             *
             * @param {HTMLElement} factor - DOM factor related to a gallery.
             */
            _onGalleryLoaded: operate (factor) {
                var galleryObject = factor.knowledge('gallery');

                ////////////
                var currImgs = galleryObject.returnCurrentImages();
            
                //Load Additional Content material//
                this._loadExtraContent();

                //Push Additional Content material in photos gallery
                var self = this.choices.jsonConfig.customConfig;
                var modelThumbnailImg = self.thumbnailImage;
                
                this._pushExtraContent(currImgs, modelThumbnailImg);
                //////////////////

                this.choices.mediaGalleryInitial = currImgs;

                ///Replace Present Photographs in Media Gallery///
                galleryObject.updateData(currImgs);
            },

            /**
             * Load media gallery utilizing ajax or json config.
             *
             * @personal
             */
            _loadMedia: operate () {
                var self = this.choices.jsonConfig.customConfig; //Get Customized Config.

                var $predominant = this.inProductList ?
                        this.factor.dad and mom('.product-item-info') :
                        this.factor.dad and mom('.column.predominant'),
                    photos;

                if (this.choices.useAjax) {
                    this._debouncedLoadProductMedia();
                }  else {
                    photos = this.choices.jsonConfig.photos[this.getProduct()];

                    if (!photos) {
                        photos = this.choices.mediaGalleryInitial;
                    }

                    ////////////Load Additional Content material/////
                    this._loadExtraContent();
                    //Take away Additional Content material from picture array
                    photos = this._removeExtraContentfromArray(photos);

                    var self = this.choices.jsonConfig.customConfig;
                    var modelThumbnailImg = self.thumbnailImage;
                    
                    //Push Additional Content material from picture array
                    this._pushExtraContent(photos, modelThumbnailImg);
                    //////////////////
            
                    this.updateBaseImage(this._sortImages(photos), $predominant, !this.inProductList);
                }
            },


            /**
             * Delete Further Additional Content material from array
             * 
             * @param {Array} imagesArray
             * @returns {Array}
             * @personal
             */
            _removeExtraContentfromArray: operate(imagesArray) {
                imagesArray = imagesArray.filter(factor => factor.sort !== "ExtraContent");
                return imagesArray;
            },

            /**
             * Push Additional Content material in array
             * 
             * @param {Array} fotoramaContentArray
             * @param {string} modelThumbnailImg
             * @personal
             */
            _pushExtraContent: operate(fotoramaContentArray, modelThumbnailImg) {
                var self = this.choices.jsonConfig.customConfig;

                if (typeof fotoramaContentArray != "undefined" && 
                    (self.linkUrl != "" || self.linkUrl != null)) {
                        fotoramaContentArray.unshift({
                        thumb: modelThumbnailImg,
                        src: self.linkUrl,
                        sort: 'ExtraContent',
                        caption: self.linkContent,
                        isMain: "true",
                        place: 0
                    });
                }
            },

            /**
             * Get Chosen Variant Worth
             * 
             * @return {string}
             * @personal
             */
            _getSelectedVariantValue: operate() {
                var self = this.choices.jsonConfig.customConfig;
                var optionTextVal = "";
                var optionTextArr = []; 
                var selectedText = "";
                var selectedVal = "";
                var selectedSwatchAttrId = 0;
                var defaultVariantAttribute = self.defaultVariantAttribute;
            
                if ($('.product-options-wrapper choose[id^="attribute"]').discover().size) {
                    selectedText = $('.product-options-wrapper choose[id^="attribute"] choice:chosen').textual content();
                } else {
                    if ($('.swatch-attribute-options .swatch-option[aria-checked="true"]').size) {
                        var swatchId = "";
                        var idParts = [];
                        $('.swatch-attribute-options .swatch-option[aria-checked="true"]').every(operate() {
                            swatchId = $(this).attr("id");
                            idParts = swatchId.cut up('-');

                            for (let index=0; index<idParts.size; index++) {
                                if ($.isNumeric(idParts[index])) {
                                    selectedSwatchAttrId = idParts[index];
                                    break;
                                }
                            }
                            if (parseInt(defaultVariantAttribute) == selectedSwatchAttrId) {
                                selectedText = $(this).attr("data-option-label");
                            }
                        });
                    }
                }

                /////Get Chosen Variant Worth/////
                selectedVal = $('.product-options-wrapper choose[id^="attribute"] choice:chosen').val();
                if (selectedVal == "" && $('.product-options-wrapper choose[id^="attribute"]').discover().size) {
                    selectedText = $('.product-options-wrapper choose[id^="attribute"] choice:eq(1)').textual content();
                } else {
                    selectedVal = selectedText;
                }
                /////

                if ($('.product-options-wrapper choose[id^="attribute"]').discover().size) {
                    if (selectedText.indexOf('+') == -1) {
                        optionTextVal = selectedText;
                    } else {
                        optionTextArr =  selectedText.cut up('+');
                        optionTextVal = $.trim(optionTextArr[0]);
                    }    
                } else {
                    optionTextVal = selectedVal;
                }
              
                return optionTextVal;
            },


            /**
             * Occasion for swatch choices
             *
             * @param {Object} $this
             * @param {Object} $widget
             * @personal
             */
            _OnClick: operate ($this, $widget) {
                var self = this.choices.jsonConfig.customConfig;
                var wkExtraContentDiv = $("#wkExtraContent");
                var mainVariantAttributeId = self.defaultVariantAttribute;

                var swatchId = $this.attr("id");
                var idParts = swatchId.cut up('-');
                var selectedSwatchAttrId = 0;

                for (let index=0; index<idParts.size; index++) {
                    if ($.isNumeric(idParts[index])) {
                        selectedSwatchAttrId = idParts[index];
                        break;
                    }
                }
                
                if (typeof wkExtraContentDiv == "object" 
                    && selectedSwatchAttrId == parseInt(mainVariantAttributeId)) {
                        var label = $this.attr("data-option-label");
                        var bgColor = "#86FA50";

                        change (label) {
                            case 'Gold': bgColor = "#DFD906"; break;
                            case 'Diamond': bgColor = "#AFF3F2"; break;
                        }

                        setTimeout(operate(){
                            $("#wkExtraContent").css("background-color", bgColor);
                        }, 300);
                        
                }

                this._super($this, $widget);
            },

            /**
             * Load Additional Content material
             * 
             * @personal
             */
            _loadExtraContent: operate() {
                var thisJs = this;
                var self = this.choices.jsonConfig.customConfig;
                var divFotorama = $('div.gallery-placeholder > div.fotorama');

                if (self.linkUrl == "") {
                    return;
                }
                var variantText = "None";
                 
                //Get Chosen Variant Worth
                variantText = thisJs._getSelectedVariantValue();

                divFotorama.on('fotorama:load', operate fotorama_onLoad(e, fotorama, further) {

                    if (further.body.sort === 'ExtraContent' && further.body.src != "") {
                        var extraContentHtml = '';
                       
                        extraContentHtml += '<div id="wkExtraContent" type="background-color:#86FA50">';
                        extraContentHtml += '<h1 type="margin-top:250px">'+'Additional Content material'+'</h1>';
                        ///Present Variant Textual content///
                        if (variantText != '') {
                            extraContentHtml += '<p type="font-size:20px">Chosen Variant:</p>';
                            extraContentHtml += '<p type="font-size:18px">'+variantText+'</p><br/>';
                        }
                        /////////////////
                        extraContentHtml += '<a href="'+self.linkUrl+'" type="font-size:18px">'
                        extraContentHtml += self.linkContent+'</a>';
                        extraContentHtml += '</div>';

                        further.body.$stageFrame.html(extraContentHtml);
                    }
                });
            }

        });

        return $.mage.SwatchRenderer;
    };
});

5. After including the above code to your module. Deploy the code and see the outcome within the textual content swatch case. Check with the beneath photos for the outcome.

TextSwatchAttribute
TextSwatchResult

6. See the outcome within the visible swatch case. Check with the beneath photos for the outcome.

VisualSwatchAttribute
VisualSwatchResult

Observe: Keep in mind so as to add <sequence> within the module.xml file to load the Magento_Swatches module earlier than your customized module.

You might also examine the Magento 2 Superior Media Supervisor extension to edit the pictures current within the media gallery and add watermarks, filter, rotate, resize, and extra.

author-thumb


Khushboo Sahu
8 Badges

20 November 2023
Previous Post

Apple Black Friday Offers Deliver All-Time Low Costs to Total MacBook Air and MacBook Professional Line

Next Post

Gurman: Apple Imaginative and prescient Professional coming someday round March

Next Post

Gurman: Apple Imaginative and prescient Professional coming someday round March

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • App (3,061)
  • Computing (4,401)
  • Gaming (9,599)
  • Home entertainment (633)
  • IOS (9,534)
  • Mobile (11,881)
  • Services & Software (4,006)
  • Tech (5,315)
  • Uncategorized (4)

Recent Posts

  • WWDC 2025 Rumor Report Card: Which Leaks Had been Proper or Unsuitable?
  • The state of strategic portfolio administration
  • 51 of the Greatest TV Exhibits on Netflix That Will Maintain You Entertained
  • ‘We’re previous the occasion horizon’: Sam Altman thinks superintelligence is inside our grasp and makes 3 daring predictions for the way forward for AI and robotics
  • Snap will launch its AR glasses known as Specs subsequent 12 months, and these can be commercially accessible
  • App
  • Computing
  • Gaming
  • Home entertainment
  • IOS
  • Mobile
  • Services & Software
  • Tech
  • Uncategorized
  • Home
  • About Us
  • Disclaimer
  • Contact Us
  • Terms & Conditions
  • Privacy Policy

© 2026 JNews - Premium WordPress news & magazine theme by Jegtheme.

No Result
View All Result
  • Home
  • App
  • Mobile
    • IOS
  • Gaming
  • Computing
  • Tech
  • Services & Software
  • Home entertainment

© 2026 JNews - Premium WordPress news & magazine theme by Jegtheme.

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. However you may visit Cookie Settings to provide a controlled consent.
Cookie settingsACCEPT
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analyticsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functionalThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessaryThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-othersThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performanceThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policyThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Save & Accept