Magento 2 How To Use jQuery Library

jQuery library is the widely used core library with rich set of functionality which includes basic regular and mostly used page functions to work with page layout and elements. This helps to manage page content, modify the page level changes and manage events via JavaScript.

jQuery in Magento 2 we can use it with simplicity with the help of require js where we need to include the jquery in the following given code snippet. This will load the jQuery on Magento pages where we call this js code on any page.

Including jQuery code inside require function in Magento 2:

require(['jquery', 'jquery/ui'], function($){ 
     //your custom js code here  
 });

Examples:

Inside the require function, we can directly access jQuery functionality by using either jQuery or it’s short form alias, the dollar $ sign. For example with jQuery keyword, we can call like below:

require(['jquery', 'jquery/ui'], function($){
  jQuery(document).ready( function() {
    alert("Page loaded jQuery.");
  });
});

Example with the $ alias:

require(['jquery', 'jquery/ui'], function($){
  $(document).ready( function() {
    alert("Page loaded jQuery.");
  });
});

Hope this helps you guys!

Leave a Reply