I'm trying to change the Masonry number of columns with a script in jQuery. This scripts reduce the max-width of Masonry container to force show only one column. The Script works almost fine, because I need to make double click to get my changes done. ¿Is it possible to make it with only one click?
This is my script:
$('.grid').masonry({
itemSelector: '.grid-item',
columnWidth: '.grid-sizer',
percentPosition: true,
gutter: 24,
});
$(document).ready(function() {
$('.button-one').on('click', function() {
$('.grid').masonry({
itemSelector: '.grid-item',
columnWidth: '.grid-sizer',
percentPosition: true,
gutter: 24,
});
$('.grid').css({'max-width': '600px'});
});
});
I have a Codepen demo with all the files:
One possible way to do this:
$('.button-one').on('click', function() {
$('.grid').css({'max-width': '600px'})
.masonry('layout');
});
Demo. See, you don't need to reinitialize the whole plugin: just command it to relayout the existing items with existing rules, based on the new dimensions of a grid container.
The way it stands, the plugin is first called again (making all the calculations using the existing style of a container), and only after that you change max-width
of a grid. The second click works ok, as dimensions are already changed.