Images height and position problem – masonry, isotope

With the responsive web design, people started to resize windows to see how well websites adapts. Of course if they came exactly for that. Normal visitors that came to read or see something don’t do that. But anyway lately I saw a lot more websites that are using masonry or isotope. Probably because it have this nice “shuffle” effect when resizing (also sorting). It works by geting absolute positions and dimensions of elements. The problem is, that in the responsive design (or fluid) we don’t specify image dimension so it could resize nicely. I will be reffering to Masonry as it’s totally free to use but the solution applies to isotope as well.

Problem

In jQuery we usually initiate things in $(document).ready(). So if you initialize masonry like this:

$(function(){
	var $container = $('#container');
	// initialize
	$container.masonry({
		itemSelector: '.item'
	});
});

and you have images inside your item without specifying dimensions you can get this:

image-issue-1

That’s not good. Images are overlaping each other. My cats are NOT happy.

Why images are overlapping each other?

As I wrote at the beginning, libraries are getting absolute positions and dimensions. Obviously you can’t get proper values of something that doesn’t exist yet. By placing initialization in $(document).ready() almost certainly you will face this issue in first page load. Why? Because it’s fired when document is ready, and it’s usually much earlier than all images are. There is a chance that next time it’s gonna be fine if browser use cached images.

Solution number 1

Just place masonry initialization in $(window).load() instead of $(document).ready().

$(window).load(function(){
	var $container = $('#container');
	// initialize
	$container.masonry({
		itemSelector: '.item'
	});
});

That way it will initialize AFTER all resources are loaded. At this point we can get correct values and it looks good

image-issue-2

and my cats are happy ;o)

Solution number 2

Waiting untill all resources are loaded is a good solution if you don’t have that many resources to load. If you have lots of them you should look into imagesLoaded. The solution with imagesLoaded is actually described on masonry appendix page therefore I’m not gonna repeat it :o)

 

5 3 votes
Article Rating