I've a problem to include Masonry JS to my Magento 2.2
I've a custom theme in app/design/frontend/CustomVendor/CustomTheme In this folder I've a web/ folder and inside I've requirejs-config.js
var config = {
map: {
'*': {
'masonry' : 'js/masonry.pkgd.min'
}
},
deps: [
"js/custom-masonry"
]
};
In this same folder I've js/ folder. Inside I've custom-masonry.j
require([
'jquery',
'masonry',
'domReady'
], function (,ドル domReady, masonry) {
console.log("custom-masonry.js");
domReady(function() {
console.log("domReady");
$('.contents-items').masonry({
columnWidth: 200,
itemSelector: '.content-items'
});
});
});
Console show me that enter image description here I think the problem is when jQuery is loaded and it's loaded before my Masonry.
2 Answers 2
Please move 'domReady' before 'masonry' in require or update you js with following.
require([
'jquery',
'domReady',
'masonry'
], function (,ドル domReady, Masonry) {
domReady(function() {
console.log("domReady");
var elem = document.querySelector('.contents-items');
var msnry = new Masonry( elem, {
itemSelector: '.content-item'
});
});
});
-
Done, but now I've a other error -> Uncaught TypeError: $(...).masonry is not a functionDevFromBelgium– DevFromBelgium2017年10月26日 13:30:30 +00:00Commented Oct 26, 2017 at 13:30
-
Please try my updated ansAasim Goriya– Aasim Goriya2017年10月26日 13:36:12 +00:00Commented Oct 26, 2017 at 13:36
Aasim's answer looks to be correct as you need to use the vanilla JS method, if not then this is how I got it working.
I implemented it so it can easily be reused in other templates just by passing the parent and child through in the x-magento-init script.
Require Config
var config = {
map: {
'*': {
masonry: 'js/vendor/masonry/masonry.min',
masonryInit: 'js/masonry-init',
}
}
};
masonry-init.js
define(['jquery', 'masonry', 'domReady!'], function(,ドル Masonry) {
return function(config) {
var brandsLayout = {
init: function() {
this.initMasonry();
},
initMasonry: function() {
var msnry = new Masonry( config.masonryParent, {
columnWidth: config.masonryChild,
itemSelector: config.masonryChild,
horizontalOrder: true,
percentPosition: true
});
}
};
brandsLayout.init();
};
});
And in my PHTML template
<script type="text/x-magento-init">
{
".brands-page": {
"masonryInit": {
"masonryParent": ".brands-page__brands",
"masonryChild": ".brands-page__collection"
}
}
}
</script>
-
1Note I use
domReady!with an exclamation mark so I don't have to use thedomReady()function.Ben Crook– Ben Crook2017年10月26日 14:18:55 +00:00Commented Oct 26, 2017 at 14:18
Explore related questions
See similar questions with these tags.