Magento 2: on swatch image hover upadate product image on category page
-
22-03-2021 - |
Question
How to update the swatch image on hover rather than click ?
I have created the custom module to show the color count,here is my code:
<?php
namespace Swatch\SwatchCount\Block\Product;
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct {
public function getProductDetailsHtml(\Magento\Catalog\Model\Product $product) {
if ($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
$_children = $product->getTypeInstance()->getUsedProducts($product);
foreach ($_children as $child){
$colorarr[$child->getColor()] = $child->getColor();
}
if(count($colorarr) > 0) { ?>
<div class="color-total">
<?php
if(count($colorarr) == 1){
$cc= 'Colour';
}else{
$cc= 'Colours';
}
echo count($colorarr)." ".$cc; ?>
</div>
<?php }
}
$renderer = $this->getDetailsRenderer($product->getTypeId());
if ($renderer) {
$renderer->setProduct($product);
return $renderer->toHtml();
}
return '';
}
}
Please guide me to do the next part, Thanks
La solution
Custom/Configupdate/view/frontend/requirejs-config.js
var config = {
map: {
'*': {
'Magento_Swatches/js/swatch-renderer' : 'Custom_Configupdate/js/swatch-renderer',
'magento-swatch.renderer' : 'Magento_Swatches/js/swatch-renderer',
}
}
};
Custom/Configupdate/view/frontend/web/js/swatch-renderer.js
define([
'jquery',
'jquery/ui',
'magento-swatch.renderer'
], function($){
$(document).on('hover','.product-item-details .swatch-attribute .swatch-option',function($this, $widget){
var proID= $(this).closest('.product-item-info').attr('id');
var swatchID = this.id;
$('#'+proID+' #'+swatchID).click();
});
});
In list.phtml file added id="prod-id<?php echo $_product->getId(); ?>"
<div id="prod-id<?php echo $_product->getId(); ?>" class="product-item-info" data-container="product-grid category-products-grid">
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange