Yassine Laadraoui
Yassine Laadraoui

Reputation: 78

setTimeout function is not working

The problem is that it keeps scrolling endlessly with no end i tried to terminate it using exit but it's not working, any solution ?
Learn More

<script>
    var marginY = 0;
    var destination= 0;
    var speed = 10;
    var scroller = null;


    function initScroll(elementId)
        {
            destination= document.getElementById(elementId).offsettop;
            scroller = setTimeout(function(){initScroll(elementId);},1);
            marginY = marginY + speed;
            if(marginY >= destination)
            {
                clearTimeout(scroller);



            }
            window.scroll(0,marginY);
    }   


</script>

Upvotes: 0

Views: 153

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

JavaScript is CaSe SeNsItIvE! It is offsetTop and not offsettop:

destination = document.getElementById(elementId).offsetTop;

On a different note, I am not sure how that does work. If you are trying a smooth scroll, you can also use jQuery by:

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

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

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

Upvotes: 3

Related Questions