Reputation: 25
I am looking to effectively intercept any calls to .scrollTo and check whether the element is a certain one so that I can stop the browser from scrolling to that element. The JavaScript file that runs the .scrollTo is out of my control, hence the need to intercept it.
Here is the code I have so far:
var oScrollTo = scrollTo;
HTMLElement.prototype.scrollTo = function(){
var scrollId = this.id;
if ( scrollId !== 'id-of-element') {
console.log("yes");
$(scrollId).oScrollTo();
} else {
console.log("no");
}
};
It's basically a combination of this answer: https://stackoverflow.com/a/1740510 and this answer: https://stackoverflow.com/a/19209665
Currently, it intercepts the .scrollTo call and logs "yes" if it's not the matching element and "no" it is.
However, it should still run .scrollTo in the normal way when "yes" is logged but it does not. Any ideas on how I can make that happen would be appreciated! Thanks!
Upvotes: 1
Views: 681
Reputation: 1517
Your code is mostly right, but you are not attaching the orgScrollTo in the appropriate location to do what you are trying. Try something along these lines:
HTMLElement.prototype.orgScrollTo = HTMLElement.prototype.scrollTo;
HTMLElement.prototype.scrollTo = function(){
var scrollId = this.id;
if ( scrollId !== 'id-of-element') {
console.log("yes");
this.orgScrollTo();
} else {
console.log("no");
}
};
Upvotes: 1