• Skip to main content

Julian Thomas Screawn

B.A. ,B.ED. ,M.ED.

  • Home
  • About
  • Computer Upgrades
  • Projects
  • Resources
  • Coding
  • Contact

Simple Smooth Scroll Script

2023/09/26

jQuery(document).ready(function($) {
	
        window.smoothScroll = function (target) {
            var scrollContainer = target;
            do { //find scroll container
                scrollContainer = scrollContainer.parentNode;
                if (!scrollContainer) return;
                scrollContainer.scrollTop += 1;
            } while (scrollContainer.scrollTop == 0);

            var targetY = 0;
            do { //find the top of target relatively to the container
                if (target == scrollContainer) break;
                targetY += target.offsetTop;
            } while (target = target.offsetParent);

            scroll = function (c, a, b, i) {
                i++; if (i > 30) return;
                c.scrollTop = a + (b - a) / 30 * i;
                setTimeout(function () { scroll(c, a, b, i); }, 20);
            }
            // start scrolling
            scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
        }

});

<a style="margin-top: 2rem;" class="cta-grey" href="javascript:void(0);"
                        onclick="smoothScroll(document.getElementById('scroll-div'))">Link Text</a>

Filed Under: JQuery, Wordpress

Copyright © 2023 · Servicing Moncton, Dieppe, Riverview and beyond! · Moncton Meditation · Moncton English Tutor