How To

How to Create Custom jQuery Widget in Magento 2?

Hello Magento Friends,

In today’s blog, we will learn How to Create a Custom jQuery Widget in Magento 2.

In Magento 2, a jQuery widget is a modular and reusable JavaScript component that encapsulates a specific behavior or functionality. Creating custom jQuery widgets enhances the user experience and adds interactive elements to your storefront.

Let’s learn How to Create a Custom jQuery Widget in Magento 2.

Steps to Create Custom jQuery Widget in Magento 2:

Step 1: Create one front action to call the template. Create one routes.xml file at the below path.

{{magento_root}}/app/code/Vendor/Module/etc/frontend/routes.xml

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="demo" frontName="demo">
            <module name="Vendor_Module" />
        </route>
    </router>
</config>

Note – In our routes.xml file, we have set frontname as demo. So we can access our template using storeUlr/demo/ControllerfoldeName/actionPhp

Step 2: Now create Controller action file called Index.php file at the following path

{{magento_root}}/app/code/Vendor/Module/Controller/Index/Index.php

Then add the below-mentioned code

<?php
namespace Vendor\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * Index action
     *
     * @return $this
     */    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->getBlock('page.main.title')->setPageTitle('DemoWidget');
        $this->_view->renderLayout();
    }
}

Step 3: Create an action handle in the layout folder.

{{magento_root}}/app/code/Vendor/Module/view/frontend/layout/demo_index_index.xml

And add the code as given below

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="demo.page" template="Vendor_Module::magento-widget.phtml"></block>
        </referenceContainer>
    </body>
</page>

Step 4: Create a requirejs-config.js file for js declaration.

{{magento_root}}/app/code/Vendor/Module/view/frontend/requirejs-config.js

Then add the below-mentioned code

var config = {
    "map": {
        "*": {
            "myCustomWidget": "Vendor_Module/js/my-custom-widget"
        } 
    }
};

Our widget name is myCustomWidget.

Step 5: Create a my-custom-widget.js file for declaring widget.

{{magento_root}}/app/code/Vendor/Module/view/frontend/web/js/my-custom-widget.js

Use the code mentioned below

define([
    'jquery',
    'jquery/ui'
    ], function($){
        $.widget('mage.myCustomWidget', {
            options: {
                abcd: 1,
                passvalue:'test'
            },
            /**
             * Widget initialization
             * @private
             */             _create: function() {
                 
            }
        });

    return $.mage.myCustomWidget;
});

Step 6: Create a template magento-widget.phtml file.

{{magento_root}}/app/code/Vendor/Module/view/frontend/templates/magento-widget.phtml

And finally, add the below code-snippet

<div class="maindiv">
    <div class="secondary">
        Widget Example using Magento 2
    </div>
</div> 
<script type="text/x-magento-init">
    {
        ".maindiv": {
            "myCustomWidget": {
                "passvalue": "custom message",
                "abcd": 123
            }
        }
    }
</script>

Output: 

Conclusion:

Hence, using the above method, you can successfully create and integrate your own custom jQuery widgets into your Magento 2 website. Experiment with different widget functionalities to enhance the user experience and make your online store more dynamic and user-friendly.

Also Learn How to Create a Widget Programmatically in Magento 2.

If you come across any error while performing the above steps, you can easily connect with me through the comment section and I will quickly provide you with the solution for it.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

43 mins ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago