How to extend existing jquery widget in Magento 2?

This article will help you to understand how to extend an existing jquery widget in Magento 2. Sometimes, there may arise situations where a project requires specific/custom approach, in that case, developers need to modify the default logic.

Let's take an example where we will make certain changes to the main navigation javascript part.

The chief file responsible for the functioning of the navigation menu is menu.js located at [project_root]/lib/web/mage/ with other default js system components.

Now, if you want to extend or overwrite it, you’ll have to make sure that you follow the steps given below:

Step 1

To properly extend the parts of menu.js with our custom content, the first step is to map our js file so that the system loads it instead of the default file.

Magento uses equirejs-config.js files to successfully map js components on the system. The first thing that matters is to understand where to place requirejs-config.js. It can be placed at several levels.

We will create a file that will replace the menu.js file. Let’s call it menu-custom.js and place it under [our theme]/web/js/ directory.

Step 2

Next, we will have to create the requirejs-config.js file and place it under [our theme]/root directory. This will help us to map our file so as to replace the default one. 

var config = {
   "map": {
       "*": {
           "menu": "js/menu-custom"
       }
   }
};

Step 3

We will extend default functionality and for this, we will be using the jQuery widget factory. We will place the following code in our newly created menu-custom.js file.

define([
       'jquery',
       'jquery/ui',
       'mage/menu'
],
   function($){
       $.widget('kiwicommerce.menu', $.mage.menu, {
           _init: function () {
               console.log("This message is from menu-custom.js");
           },
           toggle: function () {
               console.log("This message is from menu-custom.js");
           }
       });
       return $.kiwicommerce.menu;
   });

Our custom widget instance called kiwicommerce.menu is extending default $.mage.menu and in this example, we will be extending two methods, that are _init and toggle. Toggle method is in charge of toggle navigation on mobile phones while the _init method is in charge of the component initialization.

Here we can add our custom logic as needed. Currently, we have added a simple console message for testing.

  • Share :