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

How to Use jQuery Library in Magento | Complete Guide

Vinh Jacker | 09-17-2024

How to Use jQuery Library in Magento | Complete Guide How to Use jQuery Library in Magento | Complete Guide

The Most Popular Extension Builder for Magento 2

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

When optimizing your Magento 2 store, balancing page load speed with the use of jQuery for an SEO-optimized and extensible frontend can be challenging. Although you might consider using an external jQuery library for features like autocomplete fields, this can increase page load times, which kills conversions.

Fortunately, Magento 2 includes a built-in jQuery library that offers the same benefits without the drawbacks. By taking advantage of this built-in library, you can maintain fast page load speeds while enjoying advantages such as SEO optimization, simplified AJAX implementation, and interactive frontend creation.

Therefore, this article will provide the basics of jQuery in Magento 2 and practical steps for using it.

How to Use jQuery Library in Magento 2

jQuery is a fast, small, and feature-rich JavaScript library. The jQuery library provides essential functions for working with elements. It facilitates managing page content, handling, modifying, and managing events using JavaScript. You can incorporate jQuery into your project with a script like this.

<script>
    require([
        'jquery'
],
function ($) {
        $("#element_example").show();
    });
</script>

Use jQuery UI in Magento 2

In addition to jQuery, there is jQuery UI, which enhances jQuery with a variety of add-ons to improve the user interface, and add effects, widgets, and themes. You can find the complete list of available tools in the official documentation. There are 3 methods to request elements from the UI library.

Method 1: Use this code below to request elements

<script>
    require([
        'jquery',
        jquery/ui
],
function ($) {
       $("#element_example").accordion();
    });
</script>

Method 2: Set up a data-mage-init configuration

<div id="element_example" data-mage-init='{"collapsible":{"openedState": "active",
"collapsible": true, "active": true, "collateral": { "openedState": "filter-active", "element": "body"
} }}'>
    <div data-role="collapsible">
        <div data-role="trigger">
           <span>Title 1</span>
        </div>
    </div>
<div data-role="content">Content 1</div>

Method 3: Configure the special type of script - text/x-magento-init


<script type="text/x-magento-init">
{
     "#element_example": { // Your selector that will use widget
          "accordion": // <?php echo                             $block->getNavigationAccordionConfig(); ?>
    }
}
<script>

Use jQuery UI in Magento 2.4.7

In Magento 2.4.7, the jQuery UI library is restructured. It was split into separate widgets that are loaded by core modules only when necessary. This change aims to enhance store performance. It means removing the jQuery/ui dependency is necessary.

Otherwise, you’ll receive a notification that your store has activated the fallback to JQueryUI Compat. However, it appears that a dependency for a jQueryUI widget is missing. Identifying and addressing this dependency will greatly enhance your site’s performance.

Below is a specific example of the correct script for Magento 2.4.7:

<script>
define([
       'jquery',
       ‘jquery-ui-modules/widget’
],
function ($) {
       ‘use strict’;
        $.widget(‘...’);
    });
</script>

To support compatibility with older versions, you also use the “delegated” dependency approach in Magento 2.4.7:

<script>
define([
        'jquery',
       ‘Magento_Ui/js/modal/modal’
],
function ($) {
        ‘use strict’;
        $.widget(‘...’);
    });
</script>

Edit methods in a widget

Magento supports the implementation of jQuery widgets through two approaches. They are mixins and custom component development. In case, you need to add new methods to existing code, mixins are a great choice. However, consider developing a custom component if you create new code from scratch.

Use Mixin

  • The first step is to create app/code/<Vendor>/<Module>/view/frontend/requirejs-config.js by adding the below-mentioned code:
var config = {
     "config": {
          "mixins": {
               "mage/tabs": {
                   '<Vendor>_<Module>/js/accordion-mixin': true
               }
          }
      }
};

  • Then, you need to create app/code/<Vendor>/<Module>/view/frontend/web/js/accordion-mixin.js in adherence to the specified Magento 2 requirements:
define([
'jquery'
], function($) {
return function (original) {
$.widget('mage.accordion', original, {
activate: function() {
// your code here
return this._super();
}
}
);
return $['mage']['accordion'];
}
});

Add methods to the widget

  • To add the method, it is necessary to create the file at app/code/<Vendor>/<Module>/view/frontend/web/js/custom-accordion.js and set up the following code:
define([
'jquery',
'jquery/ui',
'mage/accordion'
], function($) {
$.widget('vendor.customAccordion', $.mage.accordion, {
someAction: function(element_example) {
// your code here
}
});
});

  • The next step is to go to template app/code/<Vendor>/<Module>/view/frontend/templates/example.phtml and run the below-mentioned code:
<div id="elemen_examplet"></div>
<script>
require([
'jquery',
'<Vendor>_<Module>/js/custom-accordion'], function ($) {
$("#element_example").customAccordion();
$("#element_example").customAccordion("someAction");
// Calling the vidget function the way we described before
});
</script>

Wrap Up

Through this article, hope you understand and know how to use jQuery in Magento 2, which helps to enhance the functionality and user experience of your eCommerce store. By leveraging jQuery’s powerful features, you can create dynamic, interactive, and user-friendly interfaces.

Feel free to ask if you have any questions or need further assistance with jQuery in Magento 2!

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