Home > Blockchain >  Asp.net Core JQuery scroll to div on page load not working
Asp.net Core JQuery scroll to div on page load not working

Time:01-19

I have run up against a little problem. I am trying to get the page to scroll to a specific point on page load but I'm not getting anywhere. The code I have used is below. For some reason it doesn't seem to be running at all.

<script type="text/javascript">
        // scroll past header on page load
        function scrollToDiv() {
            $(document).ready(function () {
                var ele = $('html, body').animate({ scrollTop: $('#tree').position().top }, 500, 'linear');
            });
        };


        scrollToDiv();

    </script>

If you have any suggestions as to why it is not working I would certainly appreciate it.

I am building using ASP.NET Core. The above jQuery code worked on an old webforms project so I have no idea why it isn't working now.

CodePudding user response:

To do this with jQuery:

<script>
$(function(){
    const top = $('#tree').position().top;
    $('html, body').animate({ scrollTop: top }, 500, 'linear');
});
</script>

However, you don't need jQuery for this:

<script>
window.addEventListener('DOMContentLoaded', () => {
    const target = document.getElementById('tree');
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
</script>

Window: DOMContentLoaded event - Web APIs | MDN
Element.scrollIntoView() - Web APIs | MDN

  •  Tags:  
  • Related