Question

I'm currently having some problems with the jQuery isotope plugin and hashchange function. I have a grid of divs and on page load ONLY the grid-block-filter divs are showing, clicking on one of the .grid-block-filter divs brings in the relevant content, attaching a hash to the url so the user can navigate to it from elsewhere, this all works fine, here's my example though and I'll explain my problem:
jsFiddle (with hashes): http://jsfiddle.net/neal_fletcher/vcffM/9/show

jQuery:

$(document).ready(function () {

    var $container = $('#main-grid');

    if (location.hash != "") {
        var hashfilter = "." + location.hash.substr(1);
    } else {
        var hashfilter = "*";
    }

    $container.imagesLoaded(function () {
        $container.isotope({
            filter: hashfilter + '.nav-block',
            itemSelector: '.grid-block',
            animationEngine: 'best-available',
            masonry: {
                columnWidth: 4
            }
        });
    });

    $('.grid-block-filter a').click(function () {
        var selector = jQuery(this).attr('data-filter');
        var prettyselector = selector.substr(1);
        location.hash = prettyselector;
        return false;
    });

    $(window).hashchange(function () {

        if (location.hash != "") {
            var hashfilter = "." + location.hash.substr(1);
        } else {
            var hashfilter = "*";
        }


        $container.imagesLoaded(function () {
            $container.isotope({
                filter: hashfilter,
                itemSelector: '.grid-block',
                animationEngine: 'best-available',
                masonry: {
                    columnWidth: 4
                }
            });
        });
    });
});

If you click on ONE FILTER for example, this brings in the relevant content just fine, but then clicking the back button brings back ALL the content, instead of just showing the grid-block-filter as is when the page loads. Is there anyway to stop this happening? I can't figure it out. Any suggestions would be greatly appreciated!

Was it helpful?

Solution

When the user clicks the back button, then document.ready will not fire. This is the heart of the issue you are facing. One way would be to place your scripts at the bottom of the page and not in an onload method to ensure that they always execute.

Another way would be to take the approach of this StackOverflow answer: https://stackoverflow.com/a/170478/1026459

If you set history.navigationMode to 'compatible' then jQuery's ready function will fire on Back button operations

history.navigationMode = 'compatible';
$(document).ready( function(){ /* code */ });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top