{"id":3501,"date":"2017-05-04T16:16:43","date_gmt":"2017-05-04T14:16:43","guid":{"rendered":"https:\/\/florianbrinkmann.com\/en\/?p=3501"},"modified":"2020-02-09T10:59:51","modified_gmt":"2020-02-09T09:59:51","slug":"masonry-script-viewport-width","status":"publish","type":"post","link":"https:\/\/florianbrinkmann.com\/en\/masonry-script-viewport-width-3501\/","title":{"rendered":"Running masonry script depending on viewport width"},"content":{"rendered":"\n<p>My newest theme will use the <a href=\"http:\/\/masonry.desandro.com\/\">Masonry script<\/a> to display image grids. But I only need this function if the viewport is wider than a particular width. If the viewport is narrower than this width, the images are displayed below each other, and for that, I do not need to initialize the script. This post shows you how to get this behavior working.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>At first the preliminary. It is not enough to check the viewport width on page load and run the script or not, depending on the result of the viewport width test. We also want to consider the case of resizing the viewport, and then possibly run the script or destroy a running instance. Besides that, we want to make it possible to use multiple grids per page.<\/p>\n\n\n\n<p>That is the finished script (my first attempt had a small but critical error \u2014 the final version owes its smooth operation to the <a href=\"https:\/\/github.com\/desandro\/masonry\/issues\/956#issuecomment-298633439\">help of David DeSandro<\/a>):<\/p>\n\n\n<pre class=\"wp-block-code lang-javascript\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">;(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"><\/span>) <\/span>{\n    <span class=\"hljs-keyword\">var<\/span> msnry;\n    <span class=\"hljs-comment\">\/**\n     * Get the gallery grids.\n     *\n     * @type {NodeList}\n     *\/<\/span>\n    <span class=\"hljs-keyword\">var<\/span> gridElems = <span class=\"hljs-built_in\">document<\/span>.querySelectorAll(<span class=\"hljs-string\">\".gallery-grid\"<\/span>);\n\n    <span class=\"hljs-comment\">\/**\n     * Check if we have grid elements.\n     *\/<\/span>\n    <span class=\"hljs-keyword\">if<\/span> (<span class=\"hljs-number\">0<\/span> === gridElems.length) {\n        <span class=\"hljs-keyword\">return<\/span>\n    }\n\n    <span class=\"hljs-comment\">\/**\n     * Function for creating and destroying the masonry grids.\n     *\/<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">masonryGrid<\/span>(<span class=\"hljs-params\"><\/span>) <\/span>{\n        <span class=\"hljs-keyword\">var<\/span> w = <span class=\"hljs-built_in\">Math<\/span>.max(\n            <span class=\"hljs-built_in\">document<\/span>.documentElement.clientWidth,\n            <span class=\"hljs-built_in\">window<\/span>.innerWidth || <span class=\"hljs-number\">0<\/span>\n        );\n\n        <span class=\"hljs-comment\">\/**\n         * Only init masonry if the window is greater or equal 730px\n         *\/<\/span>\n        <span class=\"hljs-keyword\">if<\/span> (w &gt;= <span class=\"hljs-number\">730<\/span> &amp;&amp; !msnry) {\n            <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">var<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; gridElems.length; i++) {\n                msnry = <span class=\"hljs-keyword\">new<\/span> Masonry(gridElems&#91;i], {\n                    <span class=\"hljs-attr\">itemSelector<\/span>: <span class=\"hljs-string\">\".gallery-grid-item\"<\/span>,\n                    <span class=\"hljs-attr\">columnWidth<\/span>: <span class=\"hljs-number\">1<\/span>,\n                    <span class=\"hljs-attr\">gutter<\/span>: <span class=\"hljs-number\">0<\/span>,\n                    <span class=\"hljs-attr\">transitionDuration<\/span>: <span class=\"hljs-number\">0<\/span>,\n                    <span class=\"hljs-attr\">resize<\/span>: <span class=\"hljs-literal\">true<\/span>,\n                    <span class=\"hljs-attr\">fitWidth<\/span>: <span class=\"hljs-literal\">true<\/span>\n                });\n            }\n        } <span class=\"hljs-keyword\">else<\/span> <span class=\"hljs-keyword\">if<\/span> (w &lt; <span class=\"hljs-number\">730<\/span> &amp;&amp; msnry) {\n            <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">var<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; gridElems.length; i++) {\n                msnry = Masonry.data(gridElems&#91;i]);\n                msnry.destroy();\n            }\n            msnry = <span class=\"hljs-literal\">null<\/span>;\n        }\n    }\n\n    <span class=\"hljs-built_in\">document<\/span>.addEventListener(<span class=\"hljs-string\">\"DOMContentLoaded\"<\/span>, masonryGrid);\n    <span class=\"hljs-built_in\">window<\/span>.addEventListener(<span class=\"hljs-string\">\"resize\"<\/span>, masonryGrid);\n})();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>At first, we create the <code class=\"lang-javascript\">msnry<\/code> variable and get a NodeList of all elements which should become Masonry grids later. After checking if we have items in the NodeList, it follows the <code class=\"lang-javascript\">masonryGrid()<\/code> function which is responsible for initializing the masonry script.<\/p>\n\n\n\n<p>In the function, we look for the current viewport width and save it. After that, we check if the result is larger than or equal <code class=\"lang-javascript\">730<\/code> and if the Masonry variable does not contain something. If this test fails, that means that the Masonry instance(s) are already running and we do not need to initialize them.<\/p>\n\n\n\n<p>Afterward, we loop through the grid elements and create a Masonry grid for each (the instance of the last run remains in <code class=\"lang-javascript\">msnry<\/code>). If the width is smaller than <code class=\"lang-javascript\">730<\/code> and <code class=\"lang-javascript\">msnry<\/code> contains something, we loop again and destroy the Masonry instances. After that, we set the <code class=\"lang-javascript\">msnry<\/code> value to <code class=\"lang-javascript\">null<\/code>.<\/p>\n\n\n\n<p>Finally, we insert two event listeners, so that the function is called on page load and resizing of the viewport.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>My newest theme will use the Masonry script to display image grids. But I only need this function if the viewport is wider than a particular width. If the viewport is narrower than this width, the images are displayed below each other, and for that, I do not need to initialize the script. This post [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"wpf_show_in_dewp_planet_feed":false,"flobn_post_versions":"","webmentions_disabled_pings":false,"webmentions_disabled":false,"lazy_load_responsive_images_disabled":false,"footnotes":""},"categories":[6],"tags":[],"class_list":["post-3501","post","type-post","status-publish","format-standard","hentry","category-web-development"],"wp-worthy-pixel":{"ignored":false,"public":"669a1797e5374aa89c64fa66e2754b1d","server":"vg07.met.vgwort.de","url":"https:\/\/vg07.met.vgwort.de\/na\/669a1797e5374aa89c64fa66e2754b1d"},"wp-worthy-type":"normal","_links":{"self":[{"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/posts\/3501","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/comments?post=3501"}],"version-history":[{"count":2,"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/posts\/3501\/revisions"}],"predecessor-version":[{"id":5892,"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/posts\/3501\/revisions\/5892"}],"wp:attachment":[{"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/media?parent=3501"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/categories?post=3501"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/florianbrinkmann.com\/en\/wp-json\/wp\/v2\/tags?post=3501"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}