How to change Product Image on Product View Page Dynamically in Magento 2
Today we’ll see how to change the product image on the product view page dynamically.
So before changing the product image let’s understand how the product image section is implemented on the product view page. For rendering product images Magento 2 uses ‘Gallery Widget’ which is a Magento UI jQuery widget. This widget implements a content area with images organized into preview and thumbnail blocks. This gallery widget uses the jQuery Fotorama widget.
To change the product image first we will get the Fotorama API object using the below code.
require(['jquery'], function ($) {
var fotoramaApi = null;
$(window).on('load',function () {
fotoramaApi = getFotoramaApi();
console.log(fotoramaApi);
});
function getFotoramaApi(){
return $('[data-gallery-role="gallery"]').data('fotorama');
}
});
Note – You have to add your all jQuery code in a file that will render on the product view page. For example, you can add your file in the head section of the catalog_product_view.xml layout file.
In the above jQuery code we have used ‘$(window).on(‘load’, function(){…});’ so that it will wait for all the images and text assets to finish loading before executing, this will let ‘Gallery Widget’ to initialize first. The ‘$(‘[data-gallery-role=”gallery”]’)’ is the element on which the Fotorama widget is initialized.
Now we have got the Fotorama API object, it’s time to change the product image with the help of some methods provided by the Fotorama API object.
//load the fotorama widget with new data
fotoramaApi.load([
{ img: 'https://ucarecdn.com/8e1e4402-84f0-4d78-b7d8- c48ec437b5af/-/stretch/off/-/resize/760x/',
thumb: 'https://ucarecdn.com/8e1e4402-84f0-4d78-b7d8-c48ec437b5af/-/stretch/off/-/resize/100x/'
}
]);
//or you can push the image in the set of frames
fotoramaApi.push(
{ img: 'https://ucarecdn.com/8e1e4402-84f0-4d78-b7d8-c48ec437b5af/-/stretch/off/-/resize/760x/',
thumb: 'https://ucarecdn.com/8e1e4402-84f0-4d78-b7d8-c48ec437b5af/-/stretch/off/-/resize/100px/'
}
);
//and show that frame (this will preview the last frame)
fotoramaApi.show('>>');
Now you know how to change the product image on the view page, try changing the image by taking the image from the user’s input and showing that image.