Javascript Workaround – What to do if ScrollTop always return zero?

View QuestionsCategory: CodeJavascript Workaround – What to do if ScrollTop always return zero?
admin Staff asked 11 months ago

For strange reason, jQuery always return zero for scrollTop() function. Have trouble scrolling to that element.

 

var target = jQuery('#element');
target.scrollTop(); //this always return zero!
1 Answers
Best Answer
admin Staff answered 11 months ago

There are workarounds:
1 – use the base javascript method (see below)
2 – use scrollBy instead of scrollTo
 


//here is workaround
var screenTop = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
var target = jQuery('#element');
targetTop = target[0].getBoundingClientRect().top
var totalTop = screenTop + targetTop; // this replaces scroll top


//if you are scrolling to a target element, can use scrollBy instead
var target = jQuery('#element');
window.scrollTo(0, target.scrollTop());
window.scrollBy(0, target[0].getBoundingClientRect().top); //easier than the above