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:

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().

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)

 

  • Share it on Twitter
  • Share it on Facebook
  • Share it on Pinterest
  • Share it on Google+
  • Share it on LinkedIn

Comments (13)Add comment

Take part in the discussion

Use pastebin.com or jsfiddle.net to add your code snippets
Your email address will not be published.