How to create a jQuery widget in Magento 2

How to create a jQuery widget in Magento 2

No doubt when things revolve around jQuery widget and that too in Magento 2, it becomes more tricky and takes hours to see final results on screen. Hence we from KiwiCommerce are going to teach you how to create a jQuery widget in Magento 2 following a set of simple steps mentioned below:

  1. Set up a module and select any PHTML file for calling custom jQuery widget.
  2. Create a custom jQuery widget.
  3. data-mage-init attribute for calling the newly created custom widget.
  4. Clear cache and check the form.

1. Set up a module and select any PHTML file for calling custom jQuery widget.

Here to start you need to create a module and override any phtml file to call your custom widget. In this example, we have contact phtml file.

2. Create a custom jQuery widget.

Next is to create a custom js file for creating custom jquery widget

And below is the basic code structure

In Define section state the jquery name that you want or else you can just give jQuery in define section.
We will be using only jQuery and jQueryUi, as a result, we will remove the extra define code from Js.
And your code will look like below:

3. data-mage-init attribute for calling your custom Widget.

Now let’s get back to our file:

In this file we need to check the number of characters for the textarea field and to do so we need to call our custom jQuery widget as shown in below code:

Where : KiwiCommerce_LoginAsCustomer/js/kiwicount is the path of JS file
Maxlen variable to pass in jquery widget as config array we can get all these arguments there using config.maxlen
Coming back to our custom widget js file, apply the code for validation and receive the argument.

In the above code snippet, we have added a _create function which is a constructor. However, we only need to check the length of the element so we have directly received the constructor.
And we have two objects, named as config and element.

Config :
The argument which is sent with the variable to this custom jquery widget:
We can access all passing argument using config.messagebox where messagebox is the variable name.

Element :
All property of the current element from where it is called, in our case we have the element <textarea>.
We can use any property of the element using: this.element

4. Clear the cache and flush and check you phtml page(Contact page)

Clear the cache :

Clear the flush:

After that you will be able to find the changes of character limit Jquery widget working on contact us page textarea.

Now, you are completely aware of jQuery widget creation specifically in Magento 2. Even if you stuck while creating widget we at KiwiCommerce all time available to help you out. Feel free to reach us. 🙂

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *