Introduction
Working with Magento 2 can sometimes feel complex, especially when dealing with JavaScript components like jQuery widgets. Unlike simple front-end tweaks, creating a custom widget requires proper structure, configuration, and integration.
If you’ve ever struggled to get your custom functionality working or spent hours debugging, you’re not alone. The good news is that once you understand the process, it becomes much easier to implement.
In this guide, we’ll walk you through how to create a jQuery widget in Magento 2, using a clear and practical step-by-step approach.
Why Use jQuery Widgets in Magento 2?
Before jumping into the steps, it’s worth understanding why jQuery widgets are useful.
They allow you to:
- Add custom front-end functionality
- Improve user experience
- Create reusable components
- Handle dynamic interactions easily
For example, you can use a widget to validate form fields, create sliders, or display live character counts like we’ll be doing in this guide.
Steps to Create a jQuery Widget in Magento 2
Follow these simple steps to create and implement your own custom widget.
1. Set Up a Module and Choose a PHTML File
The first step is to create or use an existing Magento 2 module. You’ll also need a .phtml file where the widget will be applied.
In this example, we are using the contact form template:
app/design/frontend/VendorName/ModuleName/Magento_Contact/templates/form.phtml
This file will allow us to apply the widget to a textarea field and display a live character counter.
2. Create a Custom jQuery Widget
Next, create a JavaScript file for your custom widget.
File path:
app/code/VendorName/ModuleName/view/frontend/web/js/kiwicount.js
Basic Widget Structure
Start with a simple structure like this:
define([
  ‘jquery’,
  ‘jquery/ui’
], function ($) {
  ‘use strict’;
  $.widget(‘mage.kiwicount’, {
      // Custom logic goes here
  });
  return $.mage.kiwicount;
});
What This Does
- define() loads required dependencies
- jquery/ui enables widget functionality
- $.widget() defines your custom widget
This is the base structure where you’ll add your custom functionality.
3. Call the Widget Using data-mage-init
Now, go back to your .phtml file and attach the widget to a field using the data-mage-init attribute.
Example Code
<textarea name=”comment” id=”comment”
title=”<?= $block->escapeHtmlAttr(__(‘Comment’)) ?>”
class=”input-text”
data-mage-init='{“VendorName_ModuleName/js/kiwicount”: {“maxlen”:”150″,”messagebox”:”charNum”}}’>
</textarea>
<span id=”charNum”></span>
Explanation
- The JSON inside data-mage-init calls your widget
- maxlen defines the maximum character limit
- messagebox defines where the message will be displayed
This step connects your frontend element with your custom widget logic.
4. Add Functionality to the Widget
Now, return to your kiwicount.js file and add the actual logic.
Example Code
define([
  ‘jquery’
], function ($) {
  ‘use strict’;
  $.widget(‘mage.kiwicount’, {
      _create: function (config) {
          var element = this.element;
          $(element).on(‘keyup’, function () {
              var max = config.maxlen;
              var len = $(this).val().length;
              if (len >= max) {
                  $(‘#’ + config.messagebox).text(‘You have reached the limit’);
              } else {
                  var remaining = max – len;
                  $(‘#’ + config.messagebox).text(remaining + ‘ characters left’);
              }
          });
      }
  });
  return $.mage.kiwicount;
});
Understanding the Code
_create() function
- This acts as the constructor
- It runs when the widget is initialised
config object
- Holds values passed from data-mage-init
- Example: config.maxlen, config.messagebox
element
- Refers to the field where the widget is applied
- In this case, the <textarea>
This setup ensures your widget dynamically tracks and updates character count.
5. Clear Cache and Test
After implementing your widget, you must clear the Magento cache to see the changes.
Commands
php bin/magento cache:clear
or
php bin/magento c:c
Then flush the cache:
php bin/magento cache:flush
or
php bin/magento c:f
Once done, visit your contact page and test the textarea field. You should see a live character counter working as expected.
Common Use Cases for jQuery Widgets
Here are a few practical ways you can use jQuery widgets in Magento 2:
- Form validation
- Input restrictions
- Dynamic UI elements
- Popups and modals
- Product filters
These small enhancements can significantly improve the user experience and help increase conversions.
Tips for Better Implementation
To get the best results from your widget:
- Keep your code clean and modular
- Avoid unnecessary dependencies
- Test across different browsers
- Use Magento’s built-in libraries where possible
- Always clear the cache after changes
When to Get Expert Help
While creating a basic widget is manageable, complex requirements may need expert support. Whether it’s custom checkout logic or advanced UI components, working with a professional team can save time and avoid errors.
Final Thoughts
Creating a jQuery widget in Magento 2 may seem technical at first, but once you understand the structure, it becomes straightforward.
By following the steps above, you can build reusable and efficient components that improve your store’s functionality and user experience.
If you run into any issues or need help with advanced customisations, it’s always a good idea to consult experienced Magento developers.