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:
//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:
jQuery(document).ready( function() {
alert("Page loaded.");
});
});
Have a look at the example with $ alias:
$(document).ready( function() {
alert("Page loaded.");
});
});
Similarly we can use jquery or call widget of magento from js file like:
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:
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.