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 ScommerceCustomviewfrontend 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 ScommerceCustomviewfrontendwebjs 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.

Discover more from WHO WILL CARE eCommerce

Subscribe now to keep reading and get access to the full archive.

Continue reading