32

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?

6
  • jquery is already added to m2. If you need jquery in your custom phtml file then use it by require.js Jan 14, 2016 at 10:10
  • yes i know that i want to use in custom theme.. i have file that are dependent on jquery library. Jan 14, 2016 at 10:11
  • 1
    use require([ 'jquery', 'jquery/ui'], function($){} Jan 14, 2016 at 10:12
  • you can add extrnal js by using <script src="[Vendor_Ext]::js/custom.js"/> Jan 14, 2016 at 10:17
  • Since when do you include js by link tag??? You have to use script tag
    – Black
    Oct 30, 2019 at 7:43

2 Answers 2

73

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

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>;

});
1
  • 3
    i tried that and it is not working can you place something according to theme. Jan 14, 2016 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.