-->

how to trigger/reload Masonry plugin on click

2019-04-29 17:26发布

问题:

Because i have different tabs, masonry is not loading the hidden items, so when i click on a new tab the images stack onto each other, i know this question has been asked before and answered with trigger masonry by clicking the tab, but how would i go about doing this without messing up the first tab.

Currently calling masonry with

$(function(){
$('#container').masonry({
// options
itemSelector : '.item',
columnWidth : 260
   });
});`
$(window).load(function(){   $('#container').masonry(); });

and the same for tab 2 but with a different ID - #container2

the tab one works perfectly but tab two stacks the images, until you resize the browser which fixes it and works as normal

回答1:

Do it like this:

$(function(){
    $('#container').masonry({
        // options
        itemSelector : '.item',
        columnWidth : 260
   });
});

var masonryUpdate = function() {
    setTimeout(function() {
        $('#container').masonry();
    }, 500);
}
$(document).on('click', masonryUpdate);
$(document).ajaxComplete(masonryUpdate);

Never worry about it again! Or, you may call it again after other animations, like:

$('#something').slideDown(600, masonryUpdate);

Even if you don't, just click anywhere in the page and masonry will update.



回答2:

Yes, you can reload masonry view on onclick event as following :-

Use $container.masonry('reload'); if it is work for you. In my case It was not work. I have done using setTimeout(function(){ $container.masonry() }, 400); . call masonry in setTimeout function.

$(document).ready(function($) {
    var $container = $('#youContainerId');
    $("#TabId").live("click",function(){
        //$container.masonry('reload');
        setTimeout(function(){ $container.masonry() }, 400);
    });
});