Question

I'm making a site where all internal links make the current page fade out and the new page fade in. This works great for me now. The problem is that I'm trying to combine it with the great masonry plugin. On the first pageload masonry does work, but I can't seem to figure out how to re-fire masonry on the newly loaded content via ajax. I should add that all the items from the current masonry get deleted, and then replaced by new ones.

The masonry code is like this:

    $container = $('#container');

    $container.imagesLoaded(function(){ 
        $container.masonry({
           itemSelector: '.item',
           transitionDuration: 0
        }); 
    });

And the ajax load code is like this:

    var newHash      = "",
        $mainContent = $("#ajaxcontainer"),
        $ajaxSpinner = $("#loader"),
        $el;

    $('.internal').each(function() {
        $(this).attr("href", "#" + this.pathname);
    }); 

    $(document).on('click', '.internal', function() {

        window.location.hash = $(this).attr("href");

    });

    $(window).bind('hashchange', function(){

        newHash = window.location.hash.substring(1);

        if (newHash) {
            $mainContent.fadeOut(500, function() {

                $ajaxSpinner.fadeIn();
                $mainContent.load(newHash + " #container", function() {
                    $ajaxSpinner.fadeOut( function() {
                        $mainContent.fadeIn(1000);
                    });
                    $('.internal').each(function() {
                        $(this).attr("href", "#" + this.pathname);
                    });        
                });

            });
        };

    });

    $(window).trigger('hashchange');

Does anyone have any input as to how to achieve this? Thank you very much.

Était-ce utile?

La solution

I finally managed to get it to work!

I hope other people will find this helpful so I'm posting it here for future reference.

One of the problems I had, seems to be that I hid the container while the data was loading. I hid it with fadeOut and fadeIn which seems to cause problems with masonry. Insted of hiding it per se, I now animate the opacity to 0 and back to 1 once the data is loaded. The script is as follows:

$(window).bind('hashchange', function(){

    newHash = window.location.hash.substring(1);

    if (newHash) {
        $('#ajaxcontainer').fadeTo(500, 0, function() {

            $ajaxSpinner.fadeIn();
            $mainContent.empty();
            $.get(newHash, function(data){

                var $data = $(data).find("#container > *");

                $container.prepend($data).imagesLoaded(function(){
                    $container.masonry( 'prepended', $data, true );
                });

                $ajaxSpinner.fadeOut( function() {
                    $('#ajaxcontainer').fadeTo(1000, 1);
                });     
            });

        });
    };

});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top