Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break on scrollTop change?

One of js on my website causes unnecessary scroll to top of page. How to make a break in Chrome Developers Tools when js is changing scrollTop property?

like image 497
QkiZ Avatar asked Mar 21 '16 13:03

QkiZ


1 Answers

Paste the code below and then run onVerticalScroll(function(){debugger});.

Note that this will only pause when the scroll position is set explicitly via JavaScript. For example, it won't trigger if a large element temporarily disappears from the page and causes the viewport to jump up.

function onVerticalScroll(fnOnScroll){
    var originalScrollTop = getPropertyDescriptor(HTMLElement.prototype, "scrollTop");
    Object.defineProperty(HTMLElement.prototype, "scrollTop", {
        get: function(){
            return originalScrollTop.get.apply(this, arguments);    
        },
        set: function(){
            fnOnScroll();
            return originalScrollTop.set.apply(this, arguments);
        }
    });

    var originalScrollTo = window.scrollTo;
    window.scrollTo = function(){
        fnOnScroll();
        return originalScrollTo.apply(this, arguments);
    }
    var originalScrollBy = window.scrollBy;
    window.scrollBy = function(){
        fnOnScroll();
        return originalScrollBy.apply(this, arguments);
    }

    function getPropertyDescriptor(object, propertyName){
        var descriptor = Object.getOwnPropertyDescriptor(object, propertyName);
        if (!object){
            throw new Error("descriptor not found");
        }
        if (!descriptor) {
            return getPropertyDescriptor(Object.getPrototypeOf(object), propertyName);
        }
        return descriptor;
    }
}
like image 146
Matt Zeunert Avatar answered Nov 05 '22 10:11

Matt Zeunert