Magento2 Theme – How to Use jQuery Library

jquerymagento2theme

I am creating a Magento theme where I need to include jQuery.

When I add this <link src="js/jquery-1.7.1.js"/> in head. It is working but Magento javascript functions are not working. How to use the Magento 2 built in jQuery library on a custom theme?

Best Answer

If you are adding your custom js library other than jQuery then you need to include the js code inside require function like:

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

Examples:

Inside the require function, you can directly access jQuery functionality in place by using either jQuery or its short form alias, the dollar $ sign. For example:

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

Here is an example with the $ alias:

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