Scroll to Dropdown, Activate, and Offset Top

Scroll to Dropdown, Activate, and Offset Top

Kind of boring but I just came up with a solution on how to redirect to a second page, activate a Bootstrap dropdown (such as a FAQ section) and then adjust the browser window so that the div with the hashtag isn’t at the exact top of the page:

<script type="application/javascript">
    $(document).ready(function () {
        function gotoHash(id) {
            setTimeout(function() {
                var $target = $(id),
                        scrollOffset = 200,
                        y = $target.offset().top - scrollOffset;
                if ($target.length) {
                window.scrollTo(0, y);
                }
             });
            }
       if(window.location.hash) {
       gotoHash(location.hash);
       location.hash && $(location.hash + '.collapse').collapse('show');
       }
    });
</script>

The gotoHash() function finds out where the hash is located, subtracts a certain amount and adjust the y-coordinate of the window by that difference.

Tags

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *