Add custom JS or Jquery plugin in Magento 2

add customer JS or Jquery to Magento

As you might know, Magento 2 comes with some good javascript libraries like knockoutJS, requireJS, jQuery. Today we are going to cover simple way to add jquery plugin i.e. jquery_cookie in our module.

Let’s get started -:

Step 1: Create requirejs-config.js under Scommerce\Custom\view\frontend\ folder with the following code

/**
 * Copyright © 2015 Scommerce Mage. All rights reserved.
 * See COPYING.txt for license details.
 */

var config = {
    map: {
        '*': {
            jquery_cookie:           'Scommerce_Custom/js/jquery_cookie',
        }
    }
};

Step 2: Add jquery_cookie.js under Scommerce\Custom\view\frontend\web\js\ folder with downloaded jquery cookie plugin (https://github.com/carhartl/jquery-cookie)

/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		// CommonJS
		factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
........

Step 3: Now the jquery plugin has been added, now you can call jquery cookie plugin from any of your template files

<script>
        //<![CDATA[
        <strong>require(['jquery','jquery_cookie'], function($){</strong>
            $(window).load(function() {
                $.cookie.json = true;
                var customCookie = $.cookie("customCookie");

                if (customCookie != undefined) {
                    console.log(customCookie);
                    $.removeCookie("customCookie", {path: '/', domain: document.domain});
                }
            });
        });
        //]]>
</script>

The key thing to notice here is that we are using require JS as part of the first line require([‘jquery’,’jquery_cookie’] and declaring to use jquery and our newly added jquery plugin i.e. jquery_cookie. Rest of the code is very similar to normal javascript.

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

3 thoughts on “Add custom JS or Jquery plugin in Magento 2

  1. Before this article, i was in trouble and confuse while adding jquery plugin, because due to some technical differences i didn’t accomplish the tas, but now i tried again after your guidance, its almost done, there is 1 more website which i follow, cloudways help me with every platform, and i love reading and publishing about magento.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.