John Magnolia
John Magnolia

Reputation: 16793

jQuery scrollTop if URL has hash

I have wrote this simple plugin which smooth scrolls the browser window and adds the hash link to the URL.

$.fn.extend({
    scrollWindow: function(options) {
        var defaults = { duration: "slow", easing : "swing" }                 
        var options =  $.extend(defaults, options);
        return this.each(function() {             
            $(this).click(function(e) {
                var target = $(this).attr('href');
                $('html,body').animate({scrollTop: $(target).offset().top}, options.duration, options.easing, function() {
                    location.hash = target;
                });
                e.preventDefault();
            });

        });
    }
});

How do I extend this plugin so that it auto scrolls down to the section of the page if it has a hash in the URL that exists in the DOM?

I half understand how this will work by using the window.location.hash, although I am unclear where is the best to add this inside of the plugin.

Upvotes: 1

Views: 3526

Answers (1)

Rob W
Rob W

Reputation: 349032

Store the function in a separate variable, and call the function if the hash is existent. I have implemented your request such that the current location.hash is used each time $().scrollWindow is invoked. Other implementations follow the same principle.

$.fn.extend({
    scrollWindow: function(options) {
        var defaults = { duration: "slow", easing : "swing" }                 
        var options =  $.extend(defaults, options);
        var goToHash = function(target){
            $('html,body').animate({scrollTop: $(target).offset().top}, options.duration, options.easing, function() {
                location.hash = target;
            });
        };
        if(location.hash.length > 1) goToHash(location.hash);
        return this.each(function() {             
            $(this).click(function(e) {
                //Remove junk before the hash if the hash exists:
                var target = $(this).attr('href').replace('^([^#]+)#','#');
                goToHash(target);
                e.preventDefault();
            });

        });
    }
});

Upvotes: 3

Related Questions