Question

I have a jQuery script for navigation, using AJAX to fade in each page. I'm also using imagesLoaded for displaying images after fetching them from the database.

Each of these work fine on their own, and the images load perfectly when the page loads from the images page initially. However, if I use the navigation to click to the images page after loading initially from a different page, imagesLoaded doesn't fire.

imagesLoaded portion of the script:

function portfolioImages() {
    $( function() {
        var $container = $('#container');
        var $content = $container.find('#columns');

        $(document).ready(function() {
            var items = getItems();
            console.log( items );
            $content.append( $(items) );
            $content.imagesLoaded()
            .progress( onProgress )
        });
    });

    function getItems() {
        var items = '';
        for ( var i = 0; i < 1; i++ ) {
            items += getImageItem();
        }
        return items;
    }

    function getImageItem() {
        var item;
        var src;
        $.ajax({
            async: false,
            url: "images-query.php",
            dataType: "json",
            success: function(data){
                item=" ";
                for (var i in data.images) {
                    item+="<li class=\"is-loading\"><img src=\"images/"+data.images[i].filename+"\" class=\""+data.images[i].orientation+"\" /></li>";
                }
                item+=" ";
            }
        });
        console.log(item);
        return item;
    }

    function onProgress( imgLoad, image ) {
        $( image.img ).fadeIn();
        var $item = $( image.img ).parent();
        $item.removeClass('is-loading');
        if ( !image.isLoaded ) {
            $item.addClass('is-broken');
        }
    }
}

jQuery AJAX navigation portion:

var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$(document).ready(function() {
    if (pgurl == 'portfolio'){
        portfolioImages();
    }
    $("#links li a.menu").each(function(){
        if($(this).attr("href") == pgurl){
            $(this).addClass("default");
            $(this).addClass("active");
        }
    });
    $('#links a.menu.default').click(function(e) {
        e.preventDefault();
        $(this).addClass("active");
        var url = $(this).attr('href');
        $.ajax({
            url: url,
            success: function(data) {
                $('#newcontent').fadeOut(function() {
                    $(this).fadeOut();    
                    $('#links a').not( ".default" ).removeClass("active");

                    $('#defaultcontent').fadeIn(function() {
                        $(this).fadeIn();    
                        window.history.pushState(null, data, "/ajaxtransition/" + url);
                    });

                });
                if(data = 'portfolio'){
                    return false;
                }
            }
        });
    });
    $('#links a').not( ".default" ).click(function(e) {
        e.preventDefault();
        $(".active").removeClass("active");
        var url = $(this).attr('href');
        $.ajax({
            url: url,
            success: function(data) {
                $('#defaultcontent').fadeOut(function() {
                    $(this).fadeOut();    

                    $('#newcontent').fadeOut(function() {
                        $(this).load(url + ' #defaultcontent').fadeIn();
                        window.history.pushState(null, data, "/ajaxtransition/" + url);
                        var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
                        $("#links li a.menu").each(function(){
                            if($(this).attr("href") == pgurl){
                                $(this).addClass("active");
                            }
                            if($(this).attr("href") == 'portfolio'){
                                $('#newcontent').html(portfolioImages());
                            }
                        });
                    });
                });
            }
        });
    });
});

And corresponding HTML markup:

<ul id="links">
    <li><a href="portfolio" rel="portfolio" class="menu">Portfolio</a></li>
    <li><a href="about" rel="about" class="menu">About</a></li>
    <li><a href="contact" rel="contact" class="menu">Contact</a></li>
</ul>

I've tried plugging in the following snippet, found at the end of the second $('#newcontent').fadeOut(function() { ... }) section, but it hasn't yielded the right results. imagesLoaded fires on the original page when clicking on it again, not on the images page.

if($(this).attr("href") == 'portfolio'){
    $('#newcontent').html(portfolioImages());
}

How can I get imagesLoaded to fire on the images page when the proper link is clicked on?

I'm also open to suggestions for cleaning up the code. :)

Was it helpful?

Solution

JQuery's .load (http://api.jquery.com/load/) method is also asynchronous and makes use of a callback function. Try using that here:

$(this).load(url + ' #defaultcontent', function() {
     $(this).fadeIn(); 
     window.history.pushState(null, data, "/ajaxtransition/" + url);
     var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
     $("#links li a.menu").each(function(){
         if($(this).attr("href") == pgurl){
             $(this).addClass("active");
         }
          if($(this).attr("href") == 'portfolio'){
             $('#newcontent').html(portfolioImages());
          }
     });
});

Also as far as code organization I would suggest defining the callbacks elsewhere and then call them from the asynchronous function:

$(this).load(url + ' #defaultcontent', callback);

function callback() {
     $(this).fadeIn(); 
     window.history.pushState(null, data, "/ajaxtransition/" + url);
     var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
     // and so on...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top