how to refresh a part of the page when configurable variation is selected in magento 2.3
-
09-04-2021 - |
Question
I want to reload a div section on the product detail page of the configurable product when the configurable variation is selected. How do I achieve that?
require(['jquery','jquery/ui'],function($){
jQuery(document).on('click', '.swatch-option',function(){
$('#points-refresh').load(document.URL + ' #points-refresh');
})
});
points-refresh is the id of the div section I want to reload whenever I switch one configurable child product to another.
I have tried this. But this does not work. Can anyone tell me the proper way to achieve this?
Solution
I assume you are using a custom Module name "Company_MyModule"
step 1) Create requirejs-config.js under app/code/Company/MyModule/view/frontend/
File : app/code/Company/MyModule/view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Swatches/js/swatch-renderer': {'Company_MyModule/js/swatch-renderer-mixin': true},
},
}
};
Step 2) Create the JS mixin file swatch-renderer-mixin.js under app/code/Company/MyModule/view/frontend/web/js
File : app/code/Company/MyModule/view/frontend/web/js/swatch-renderer-mixin.js
define(['jquery'], function ($) {
'use strict';
var mixin = {
_OnClick: function ($this, $widget) {
//Start Write you Code here for Conf option Click event
var myDuv = '<div style="width:100%; border:1px solid #95a5a6;padding:10px 0 10px 0;"><center>An option Clicked!.</center></div>';
$(".product-add-form").prepend(myDuv);
console.log("========= Config Option OnClick ====================");
//End you code
return this._super($this, $widget);
},
_OnChange: function ($this, $widget) {
//Start Write you Code here for Conf option Change event
var myDuv = '<div style="width:100%; border:1px solid #95a5a6;padding:10px 0 10px 0;"><center>An option Change!.</center></div>';
$(".product-add-form").prepend(myDuv);
console.log("========= Config Option Change ====================");
//End you code
return this._super($this, $widget);
}
};
return function (targetWidget) {
$.widget('mage.SwatchRenderer', targetWidget, mixin);
return $.mage.SwatchRenderer;
};
});
step 3) Clean Magento cache
sudo php bin/magento cache:clean
=========== Demo ==============
OTHER TIPS
You can directly select the options by url -
https://domain.com/test8.html#319=662&322=685
https://domain.com/test8.html#super_attribute1=option-value&super_attribute2=option-value
So you can use that concept and implement.