javascriptscrollto

What happens if I override window.scrollTo method?


I am new to javascript programming, so please bear with me for a basic question :) If accidentally one of the open source javascript code modifies the native window.scrollTo() method, how can I ensure that when calling scrollTo for a HTML element, it will always work, and not raise an JS error instead?


Solution

  • You can restore the default version of scrollTo by simply deleting the modification.

    delete window.scrollTo;
    

    This will remove the modified window.scrollTo and replace it with the default version of the function from the Window object prototype.

    However, if you need the modified version of window.scrollTo you can make a copy of it and use the copy.

    Execute the following code BEFORE you load the library:

    window.scrollToProper = window.scrollTo;
    

    From then on you can call scrollToProper() to use the default function, even if window.scrollTo gets modified.

    Alternatively, you can call the default scrollTo function directly from the Window prototype. (Thanks rishabh.) The syntax is as follows:

    Window.prototype.scrollTo.call(window, x, y);
    

    Note the capitalization of Window, because you are referring to the Window object rather than the current instance.