I am writing a wordpress plugin in php. In that plugin I output pictures with a little text and want to do that with masonry.
When I initialize masonry in HTML, it seems to work, but the pictures overlap:
<div id="container" class="js-masonry" data-masonry-options='{ "columnWidth": 200, "itemSelector": ".item" }'>
Therefore I am trying to use “Imagesloaded” (by the same developer?).
But as I see it, before I can use ImagesLoaded I need to get Masonry up and running with javascript. When I initialize Masonry in my plugin_scripts.js I get an error on the frontend:
plugin_scripts.js:
jQuery(function() {
alert("hallo");
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
// options
columnWidth: 200,
itemSelector: '.item'
});
});
Console Error in Frontend:
Bad masonry element: null
masonry.min.js?ver=3.1.2:1
q masonry.min.js?ver=3.1.2:1
d masonry.min.js?ver=3.1.2:1
(anonymous function) schnoogle_scripts_frontend.js?ver=3.9.2:10
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
n.extend.ready jquery.js?ver=1.11.0:2
K jquery.js?ver=1.11.0:2
Can you help?
You should load html before call masonry so query selector can find query
It looks like Masonry can’t find your container for some reason. I assume you’ve tried the obvious, such as making sure
#container
is actually on the page.If you’re using jQuery (which you are), you can use jQuery’s selector engine.
Ensure this is within a
document.ready
call, so that you’re doing it after the rest of the page is ready.if using vanilla js in WordPress, if you enqueue a script it’s everywhere. to solve this I query to see if the element is on the page for initializing Masonry.