Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading