In this article I will tell you how to use jQuery and we will analyze how to implement your own html for frontend.
The first thing that we should know about Magento 2.0 is that unlike Magento 1.x it contains several popular frameworks such as Prototype, jQuery + plugins, Angular etc.
You may ask why so many, it can cause overload and you won’t even need half of them!
But it’s not true. Magento 2.0 analyzes JS scripts and enables only those that are pre-defined.
But how can it be done?
One of the methods is to use the command require:
1 2 3 |
require(["jquery","jquery/jquery.cookie",”<Other plugins>”], function(jQuery){ var wishlist = jQuery.cookie('guestwishlist'); // Getting data from Cookies }); |
Now we know how to use jQuery and it’s time to use it for adding extra content to page.
Magento 2.0 uses new template that is called Luma. One of the best innovations is to use the data attributes in html.
These attributes can be easily transferred from default template to customized one without affecting designer’s idea.
How can it be used in Scripts?
1 2 3 4 5 6 7 |
require(["jquery","jquery/jquery.cookie",”<Other plugins>”], function(jQuery){ jQuery(document).ready(function{ jQuery.getJSON(url,params, function(data){ jQuery('[data-role=compare-products-link]').before(data.wihlist.link); }); }) }); |
In this script we can see that we use the connection to [data-role=compare-products-link] for adding new button near “Compare Products”.
Before:
After: