Question

I am using the jQuery $(window).on('hashchange') method to hide irrelevant sections except the one that the URI-hash points to. It works beautifully, back button and everything. Except for the fact that I can't seem to prevent the default behaviour of the browsers, that is to scroll down to the section with the matching id.

Here is my function.

var AddHashNav = function (hashmatch, container) {
    $(window).on('hashchange', function (e) {
        if ( !window.location.hash ) {
            // empty hash, show only the default header
            change_preview(container, container + ' > header');
            return false;
        }
        // Don't do anything to hash links who's ids don't match
        else if ( window.location.hash.match(hashmatch) ) {
            change_preview(container, window.location.hash);
            return false;
        }
    });
}

var changePreview = function (container, preview) {
    $(container + ' >').addClass('hidden');
    $(preview).removeClass('hidden');
}

And the caller is simply

$(document).ready(function () {
    // applay AddHashNav to all sections who's id ends in 'preview'
    AddHashNav(/preview?/, '.hash-nav-container');
});

I've tried both e.preventDefault(); and return false; and neither seem to work.

Note that I'm trying to prevent the behaviour of the hashChange event, not the click event, here it seems not to be possible, but I'm sure at least somebody has managed to figure out how to do this.

Was it helpful?

Solution

I fixed it by running the change_preview() on the first call of the AddHashNav constructor, and therefor hiding the sections on the $(document).load() call.

var AddHashNav = function (hashmatch, container) {
    // hide all sections except header on load
    change_preview()
    $(window).on('hashchange', function (e) {
        if ( !window.location.hash ) {
            // empty hash, show only the default header
            change_preview(container, container + ' > header');
            return false;
        }
        // Don't do anything to hash links who's ids don't match
        else if ( window.location.hash.match(hashmatch) ) {
            change_preview(container, window.location.hash);
            return false;
        }
    });
}

It is not the most beautiful solution. I'm not sure why it works (I assume it is because the sections have no position in the window object, and hence can't be scrolled into), but it works for now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top