How to detect browser resize in Magento 2 using jQuery?

It is frequent to have requests from customers wanting to place blocks in totally different places in desktop and mobile. This type of requests do not fit the usual block placement using magento’s layout xml files. So, how can this be solved?

#1 Duplicate the block and hide one when on mobile/desktop using CSS rules

This is really not the best solution, specially if you are handling dynamic blocks. It also can result in duplicate content which is not good for SEO.

#2 Using jQuery to detect browser resize events and move the html element accordingly

This is a good approach in my book. Here is how you can implement it (include the following javascript in the page you want to make the change)

<script>
	require(['jquery', 'jquery/ui'], function($){ 
		$( window ).resize(function() {
			if ($(this).width() <= 767) {
				// Mobile
				$(<selector for the html element to move>).insertBefore(<selector of the html element that will be after>);
			}
			else {
				// Desktop
				$(<selector for the html element to move>).insertBefore(<selector of the html element that will be after>);
			}
		});
	 });
</script>

Of course you can use other jQuery function instead of insertBefore depending on where in the DOM you want to place the html element want to move.

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *