26

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?

  • jquery is already added to m2. If you need jquery in your custom phtml file then use it by require.js – Shaheer Ali Jan 14 '16 at 10:10
  • yes i know that i want to use in custom theme.. i have file that are dependent on jquery library. – Qaisar Satti Jan 14 '16 at 10:11
  • 1
    use require([ 'jquery', 'jquery/ui'], function($){} – Shaheer Ali Jan 14 '16 at 10:12
  • you can add extrnal js by using <script src="[Vendor_Ext]::js/custom.js"/> – Shaheer Ali Jan 14 '16 at 10:17
52

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.");
  });
});
  • Is it possible to include prototype.js ? – Slimshadddyyy Mar 10 '16 at 10:37
  • @Vikram, Yeah, just add 'prototype' element to the array that you pass to require() function. – Roman Glushko Jan 12 '17 at 8:27
4

Jquery/JqueryUI have added in magento2. You can see in lib/web/jquery

To use jquery or call widget of magento. From your js file

define([
  'jquery',
  'jquery/ui',
  'mage/<widget.name>' found in /lib/web/mage dir
], function($){

$.widget('<your_namespace>.<your_widget_name>', $.mage.<widget.name>, {  CODE HERE... });

return $.<your_namespace>.<your_widget_name>;

});
  • 3
    i tried that and it is not working can you place something according to theme. – Qaisar Satti Jan 14 '16 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.