:::: MENU ::::
Posts tagged with: magento 2 jquery

Use jquery magento 2

In this tutorial we will discuss Use jquery magento 2 .i.e how to use jquery in magento 2. with following example you can use jQuery in phtml file.And in this tutorial i will try to explain it briefly and also make it convenient.

Suppose you have created a Magento theme where you need to include jQuery.Usually there comes a conflict that with jquery, JavaScript functions does not work properly.In this tutorial we will learn how to use the Magento 2 built in jQuery library on a custom theme.

Since jquery is already added in magento 2.But if u want to use in custom themes, you will have to do it differently.

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

For example:
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.");
  });
});

Have a look at the example with $ alias:

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

Similarly we can use jquery or call widget of magento from js file like:

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

Furthermore if you get an error, it’s possible that it’s because of duplication of jquery.So check it and remove jquery source first, if you are getting error in page .xml file in layout folder.


then define your jQuery like:

<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
 define jquery and print message in console
<script type="text/javascript">// < ![CDATA[
        $.noConflict();
        jQuery(document).ready(function(){
       console.log('hello this is dmeo ');

 });// ]]>
</script>

That’s it from this tutorial. I hope it serves the purpose.Furthermore please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: January 1, 2019