Search code examples
javascriptsettimeoutanchor-scroll

Using jQuery's setTimout() Function For Anchor Scrolling


I'm still learning how to use jQuery and I have this script which smooth scrolls to anchors on my page. I would like it to wait a second before it begins scrolling, as I have a menu that needs to close. I assume I need to use the setTimeout() function but cannot figure out how to implement it correctly in my code below.

<script>

  $(document).ready(function(){
	$('a[href^="#"]').on('click',function (e) {
	    e.preventDefault();

	    var target = this.hash,
	    $target = $(target);

	    $('html, body').stop().animate({
	        'scrollTop': $target.offset().top - 2
	    }, 900, 'easeInOutExpo', function () {
	        window.location.hash = target;
	    });
	});
});

</script>


Solution

  • Wrap the animate in a timeout:

    setTimeout(function() {
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top - 2
        }, 900, 'easeInOutExpo', function () {
            window.location.hash = target;
        });
    }, 1000);