简体   繁体   中英

jQuery on scroll does not fired with anchor hash scroll

I am trying to track the scroll event produced by the automatic scrolling occurred due to going to anchor hash in the URL. For example http://example.com/page.html#theID it should scroll to the DOM element of id equals to theID .

I need to track this event to overcome Bootstrap navbar from covering that element by increasing its padding or scrolling to point more near than it from the top to make sure it will not be covered. I have tried the following code:

...     
<script>
        $(document).ready(function(){
          $(this).on("scroll",function(){
             alert('Scroll Event...');
          })
        })
    <script>
    </body>
    </html>

When loading the page with the anchor in the URL as described above, the above code does not work. However, it works only when I, manually, scroll the page.

Hence, Is there any way to track the automatic scroll of going to an anchor?

From this answer I have built the implementation that detect the automatic scroll and then scroll above the anchor point to solve the bootstrap's navigation bar cover of the anchor area.

<script type="text/javascript">
    autoScroll = true;
window.onscroll = function (e) {       
   if (autoScroll){ 
       axisY = e.pageY; //FireFox
       if (axisY == null){
           //It is not FireFox, 
       // it tested with Opera, Chrome, Ubuntu Web Browser, Android Browser.
           axisY = e.path[1].pageYOffset;
       }         
         $("html body").animate({scrollTop:axisY-70});
         autoScroll = false;
    }        
}

The Boolean autoScroll is to prevent stop ordinary scrolling after page load

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM