Cannot initialize Masonry with JQuery

2019-09-01 09:00发布

问题:

According to the official documentation there are different ways to initialize the masonry container. The HTML initialization works fine, but when I try to move the parameters from the data-masonry attribute to JQuery, things break.

Here is the HTML initialization with the JSON params.

<div id="container" class="masonry js-masonry"  data-masonry-options='{ "columnWidth": ".grid-sizer", "itemSelector": ".item", "isFitWidth": true }'>

And then this is what it currently looks like when I move these to my js/JQuery-file:

var $container = $('#container');
// initialize
$container.masonry({
  columnWidth: '.grid-sizer',
  itemSelector: '.item',
  isFitWidth: true
});

Using the latter version, the grid-sizer element goes visible, which should not show up, of course.

I see no specification in the official documentation about when I need to call the initialization code in JQuery. Is it $(document).ready where I can call this?

JSFIDDLE with broken layout: http://jsfiddle.net/1f1kwfbd/10/

回答1:

I see no specification in the official documentation about when I need to call the initialization code in JQuery. Is it $(document).ready where I can call this?

So you can call this whenever you want.

The quickest way would indeed be on document.ready - this would fire it as soon as the page loads e.g

$( document ).ready(function() {
    var $container = $('#container');
    // initialize
    $container.masonry({
      columnWidth: '.grid-sizer',
      itemSelector: '.item',
      isFitWidth: true
    });
});

Alternatively you could encapsulate your masonry code within a function and choose to call this at a later time. e.g

// Declare your function
function initMasonry() {
    var $container = $('#container');
    // initialize
    $container.masonry({
      columnWidth: '.grid-sizer',
      itemSelector: '.item',
      isFitWidth: true
    });
}

To call the function just call it like so:

initMasonry();

Update

After reading the docs for masonry, you need to create a new masonry object as opposed to init the masonry object on your jQuery selector.

Example code:

$(document).ready(function() {

    var container = document.querySelector('#container');
    var msnry = new Masonry( container, {
        columnWidth: '.grid-sizer',
        itemSelector: '.item',
        isFitWidth: true
    });

});

Updated fiddle: http://jsfiddle.net/pjbq4gj6/

Docs for reference: http://masonry.desandro.com/#javascript