Magento2 jQuery Plugin – How to Add a jQuery Plugin in Theme

jquerymagento2requirejs

I have been looking into RequireJS for a while, but till now, I still can not figure out how to add the TouchSwipe plugin into my theme.

Would somebody take the time to give me a step by step?

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,

var config = {
    paths: {            
            'touchswipe': "js/jquery.touchSwipe.min"
        },   
    shim: {
        'touchswipe': {
            deps: ['jquery']
        }
    }
};

Now you can use inside your template like this,

<div id="touchme">Touch me to see effect</div>

<script>
    require([
        'jquery',
        'touchswipe'
    ], function($, swipe){
        $(function() {
            $("#touchme").swipe({
                    //keep your code here
            });
        });
    });
</script>

Now

Remove var folder from root
Remove pub/static folder contents.

Run deploy command,

php bin/magento setup:static-content:deploy

Related Topic