zmanc
zmanc

Reputation: 5409

Window scroll for incoming hash path url

I have a page with some fixed and absolute elements that are causing an issue for hash path links. I was able to fix it while the user is navigating around the page with function() { window.scrollBy(0, -80) }; however if I try to call this on my document ready (to scroll for incoming hashes) it does not work.

I found the reason it does not work is that the page does not actually adjust to the hash until after the document ready. If I cannot do this at document ready when can I do it?

Upvotes: 2

Views: 979

Answers (1)

mathielo
mathielo

Reputation: 6795

As clearly the browser only scrolls to the HTML element from hash only after the whole page is loaded - including all JS -, I think the best option is to bind actions to the scroll event of the page.

You could try something like this:

<script type="text/javascript">
    $(function() {

        // Retrieves the hash from URL
        var hash = window.location.hash.substring(1);


        // If hash length > 0 (there is actually a hash)
        // And the #hash element exists on page
        if(hash.length > 0 && $('#'+ hash).size() > 0){

            // Binds a function to the page scroll
            $(document).on('scroll', function(){

                // Here's the bright part: when the browser finish loading the page, it will
                // scroll right to the #hash element. So, whenever the page is scrolled, if
                // the #hash element offset top matches the page scroll offset, it means the page
                // was scrolled right to that element.
                var elemTop = $('#'+ hash).offset().top; // Retrieve element's offset top
                var docTop = $(document).scrollTop(); // Retrieve page's offset

                if(elemTop == docTop){
                    alert('Now I do my stuff!! :)');
                    // Do your stuff
                }

                // And now you make sure "your stuff" won't happen again if the user
                // accidentally scrolls precisely to the #hash element's offset by
                // unbinding scroll action of the page.
                $(document).unbind('scroll');
            });
        }

    });
</script>

I hope that help you to solve your problem! Let me know if anything was unclear.

Upvotes: 1

Related Questions