jquery masonry collapsing on initial page load, works fine after clicking "home" menu button

John B picture John B · Mar 1, 2013 · Viewed 12.3k times · Source

My jquery masonry setup is working strangely on initial page load. It seems to be placing the images in the first row fine, the second row is positioned overlapping the first and the same for the third row. After page load, you can click the home button or the logo and reload the page and it works fine.

I have this code in the functions.php to put the masonry and jquery scripts in:

if (!is_admin()) {
    wp_enqueue_script('jquery');
    wp_register_script('jquery_min', get_template_directory_uri(). '/js/jquery.min.js', array('jquery'), '1.6.1' );
    wp_enqueue_script('jquery_min');
    wp_enqueue_script('jquery');
    wp_register_script('jquery_masonry', get_template_directory_uri(). '/js/jquery.masonry.min.js', array('jquery'), '2.1.06' );
    wp_enqueue_script('jquery_masonry');
}

This script is in the head.php:

<?php if (is_page(2)) { ?>
    <script>
        $(function(){
            $('#content').masonry({
                // options...
                itemSelector : '.product',
                columnWidth : 310,
                isAnimated: true,
                animationOptions: {
                    duration: 700,
                    easing: 'linear',
                    queue: false
                }
            });
        });
    </script>
<?php } ?>

This is a link to the site.

Any idea as to why this is loading strangely on initial page load?

I'm pretty new to scripting anything, so please be kind.

Answer

Ivan Ivković picture Ivan Ivković · Mar 1, 2013

I think it's because the script is being run before the content (images) is fully loaded. Hence the positioning error.

Try this.

  $(window).load(function()
  {
      $('#content').masonry({
           itemSelector : '.product',
           columnWidth : 310,
           isAnimated: true,
           animationOptions: {
                duration: 700,
                easing: 'linear',
                queue: false
           }
      });
  });