I have this small snippet of jQuery:

if (jQuery(window).innerWidth() > 568) {
    jQuery('#boardOfTrustees').masonry({
        itemSelector: '.postWrapper',
    });
}

This works fine, but I want to stop this from working, or uninitialize it on resize if the screen is smaller than a certain size. I've tried this:

jQuery(window).smartresize(function() {
    if (jQuery(window).innerWidth() > 568) {
        jQuery('#boardOfTrustees').masonry({
            itemSelector: '.postWrapper',
        });
    }   
});

.smartresize is a debounce script, it works well, but for this particular scenario, its not doing anything and the masonry script is still initialized. How can I make first set of jQuery stop applying itself to the elements if the screen is smaller than 568 pixels but then start working again if the resize is larger than 568?

有帮助吗?

解决方案

This would work on load. Not on resize:

if (jQuery(window).innerWidth() < 568) {
    jQuery('#boardOfTrustees').masonry({
        itemSelector: '.postWrapper',
    });
}

To make it work on resize then you would need to use the method destroy as detailed at the documentation.

$(window).resize(function () {
    if (jQuery(window).innerWidth() < 568) {
        jQuery('#boardOfTrustees').masonry('destroy');
    } else {
        jQuery('#boardOfTrustees').masonry({
            itemSelector: '.postWrapper',
        });
    }
});

其他提示

Destroy it

else {
    jQuery('#boardOfTrustees').masonry('destroy')
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top