I found a better way. It is as described bellow.
First create a module. I assume you know how to create a basic module. Then in vendor/module/view/frontend create requirejs-config.js with following code:
var config = {
"map": {
"*": {
"swiper": "Vendor_Module/js/swiper",
"swiper_init": "Vendor_Module/js/swiper_init"
}
},
"shim":{
"Vendor_Module/js/swiper": ["jquery"]
}
};
Then place swiper.js and swiper_init.js in vendor/module/view/frontend/web/js
Swiper.js is the file you downloaded from Swiper repository and in swiper_init.js place following code:
define([
"jquery",
"Vendor_Module/js/swiper"
], function($, Swiper){
$.widget('vendor.module',{
options: {
},
_create:function(config, element){
//this.enableSwiper(false);
var widget = this,
options = this.getOptions(),
swiper = new Swiper(this.element, options);
swiper.init();
},
getOptions: function(){
return this.options;
},
});
return $.vendor.module;
});
After that, add required classes to you phtml file
<div class="swiper-container" data-mage-init='{"swiper_init":{
"direction": "horizontal",
"slidesPerView": 4,
"spaceBetween": 40,
"centeredSlides": true,
"centeredSlidesBounds": true,
"breakpoints":{"375":{"slidesPerView":1},"768":{"slidesPerView":2},"1024":{"slidesPerView":1}}
}
}'
<div class="product-items swiper-wrapper">
<div class="product-item-info swiper-slide>
.....your code to get products/images etc ......
</div>
</div>
</div>
Save everything and setup:upgrade and all relevant Magento2 commands
You can also use it in any of your products widgets phtml files by declaring
<script type="text/x-magento-init">
{
"#swiper-container": {
"swiper_init": :{
"direction": "horizontal",
"slidesPerView": 4,
"spaceBetween": 40,
"centeredSlides": true,
"centeredSlidesBounds": true,
"breakpoints":{"375":{"slidesPerView":1},"768":{"slidesPerView":2},"1024":{"slidesPerView":1}}
}
}
}
}
</script>
Hope this help everyone. The best thing about this method is that it doens't use inline javascript. Also don't forget to create a default.xml file in layout folder to declare swipper.css. Most relevant code you can find in nolimitsforweb repository in Github.
Best Answer
copy js file jquery.touchSwipe.min.js into your custom theme
web/js
folder.app/design/frontend/Vendor/themename/web/js/jquery.touchSwipe.min.js
Now you have to use inside your template file,
just create requirejs-config.js file inside your theme template,
app/code/Vendor/Module/view/frontend/requirejs-config.js
code for js file,
Now you can use inside your template like this,
Now
Run deploy command,