Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

6 Easy Steps to Create A jQuery Widget in Magento 2

Vinh Jacker | 3 days ago

6 Easy Steps to Create A jQuery Widget in Magento 2 6 Easy Steps to Create A jQuery Widget in Magento 2

The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

Magento 2 jQuery widget serves as a modular and reusable JavaScript component that encapsulates specific behavior or functionality. By creating custom jQuery widgets, you can enhance the user experience by adding interactive and customized functionality. Additionally, these widgets seamlessly integrate interactive elements into your Magento 2 storefront, making your website more engaging and user-friendly.

In this article, we’ll guide you through the steps to create a custom jQuery widget in Magento 2.

Hire JavaScript Developers

  • Free 1-1 consultation to customize your solution
  • Comprehensive JavaSript services
  • Onboard within 48 hours
  • Only from $15 per hour
  • Learn more
    Hire JavaScript Developers

    Step 1: Create a Front Action and Routes

    The first step is to create one front action to call the template. Create a routes.xml file at the path:

    Mageplaza/Customize/app/code/Vendor/Module/etc/frontend/routes.xml

    Add the following code to the routes.xml file:

    <?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="mageplaza" frontName="mageplaza">
                <module name="Mageplaza_Customize" />
            </route>
        </router>
    </config>
    
    

    Step 2: Create Controller Action

    You need to create a Controller action file which is called Index.php file at the following path:

    Mageplaza/Customize/app/code/Vendor/Module/Controller/Index/Index.php

    Then add the code below

    
    <?php
    namespace Mageplaza\Customize\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

    The next step is to create an action handle in the layout folder (e.g., demo_index_index.xml).

    Mageplaza/Customize/app/code/Vendor/Module/view/frontend/layout/demo_index_index.xml

    Then add the below-mentioned code:

    <?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="Mageplaza_Customize::magento-widget.phtml"></block>
            </referenceContainer>
        </body>
    </page>
    
    

    Step 4: Declare JavaScript Dependencies

    Create a requirejs-config.js file at the path:

    Mageplaza/Customize/app/code/Vendor/Module/view/frontend/requirejs-config.js.

    Then run the following code:

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

    Step 5: Declare Your Custom Widget

    Create a my-custom-widget.js file at the path:

    Mageplaza/Customize/app/code/Vendor/Module/view/frontend/web/js/my-custom-widget.js

    Use the code mentioned in your text to declare your custom widget

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

    Step 6: Create The Widget Template

    Create a template file (e.g., magento-widget.phtml) at the path:

    Mageplaza/Customize/app/code/Vendor/Module/view/frontend/templates/magento-widget.phtml

    And then add the below-mentioned code

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

    After completing the above steps, you need to run the following commands:

    php bin/magento setup:upgrade 
    php bin/magento setup:static-content:deploy 
    php bin/magento cache:clean 
    

    This will create a module, clear the cache, and allow you to check the result.

    Wrap Up

    By following the steps outlined above, you will create and integrate your custom widget seamlessly into your Magento 2 store. These jQuery widgets in Magento 2 allow you to adjust your frontend components and provide a more engaging experience for users.

    If you need further assistance or have any questions, feel free to ask!

    Table of content
      Jacker

      With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



      Related Post

      Website Support
      & Maintenance Services

      Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

      Get Started
      mageplaza services