jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)
Yeah, there appears to be a bug in Chrome when it comes to modifying the body
, trying to make it into an offsetParent
. As a work-around, I suggest you simply add another div to wrap the #content
div, and make that scroll:
html, body { height: 100%; padding: 0; }
html { width: 100%; background-color: #222; overflow: hidden; margin: 0; }
body
{
width: 40em; margin: 0px auto; /* narrow center column layout */
background-color: white;
position: relative; /* allow positioning children relative to this element */
}
#scrollContainer /* wraps #content, scrolls */
{
overflow: auto; /* scroll! */
position:absolute; /* make offsetParent */
top: 0; height: 100%; width: 100%; /* fill parent */
}
#header
{
position: absolute;
top: 0px; height: 50px; width: 38.5em;
background-color: white;
z-index: 1; /* sit above #content in final layout */
}
#content { padding: 5px 14px 50px 5px; }
Tested in FF 3.5.5, Chrome 3.0.195.33, IE8
Live demonstration:
$(function() { $('#header').find('button').click(function(ev) { var button = $(this), target = $('div.' + button.attr('class')); var scroll = target.offsetParent().scrollTop(); target.offsetParent().scrollTop(target.offset().top + scroll - 50); }); });
html, body { height: 100%; padding: 0; } html { width: 100%; background-color: #222; overflow: hidden; margin: 0; } body { width: 40em; margin: 0px auto; background-color: white; position: relative; } #scrollContainer { overflow: auto; position:absolute; top: 0; height: 100%; width: 100%; } #header { position: absolute; top: 0px; height: 50px; width: 38.5em; background-color: white; z-index: 1; } #content { padding: 5px 14px 50px 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id='header'> Header Box <button class='A'>A</button> <button class='B'>B</button> <button class='C'>C</button> </div> <div id='scrollContainer'> <div id='content'> <div style='height: 50px'> </div> <div class='A'> <h1>A</h1> <p>My name is Boffer Bings. I was born of honest parents in one of the humbler walks of life, my father being a manufacturer of dog-oil and my mother having a small studio in the shadow of the village church, where she disposed of unwelcome babes. In my boyhood I was trained to habits of industry; I not only assisted my father in procuring dogs for his vats, but was frequently employed by my mother to carry away the debris of her work in the studio. In performance of this duty I sometimes had need of all my natural intelligence for all the law officers of the vicinity were opposed to my mother's business. They were not elected on an opposition ticket, and the matter had never been made a political issue; it just happened so. My father's business of making dog-oil was, naturally, less unpopular, though the owners of missing dogs sometimes regarded him with suspicion, which was reflected, to some extent, upon me. My father had, as silent partners, all the physicians of the town, who seldom wrote a prescription which did not contain what they were pleased to designate as _Ol. can._ It is really the most valuable medicine ever discovered. But most persons are unwilling to make personal sacrifices for the afflicted, and it was evident that many of the fattest dogs in town had been forbidden to play with me--a fact which pained my young sensibilities, and at one time came near driving me to become a pirate. </div> <div class='B'> <h1>B</h1> <p> Looking back upon those days, I cannot but regret, at times, that by indirectly bringing my beloved parents to their death I was the author of misfortunes profoundly affecting my future. <p> One evening while passing my father's oil factory with the body of a foundling from my mother's studio I saw a constable who seemed to be closely watching my movements. Young as I was, I had learned that a constable's acts, of whatever apparent character, are prompted by the most reprehensible motives, and I avoided him by dodging into the oilery by a side door which happened to stand ajar. I locked it at once and was alone with my dead. My father had retired for the night. The only light in the place came from the furnace, which glowed a deep, rich crimson under one of the vats, casting ruddy reflections on the walls. Within the cauldron the oil still rolled in indolent ebullition, occasionally pushing to the surface a piece of dog. Seating myself to wait for the constable to go away, I held the naked body of the foundling in my lap and tenderly stroked its short, silken hair. Ah, how beautiful it was! Even at that early age I was passionately fond of children, and as I looked upon this cherub I could almost find it in my heart to wish that the small, red wound upon its breast--the work of my dear mother--had not been mortal. </div> <div class='C'> <h1>C</h1> <p>It had been my custom to throw the babes into the river which nature had thoughtfully provided for the purpose, but that night I did not dare to leave the oilery for fear of the constable. "After all," I said to myself, "it cannot greatly matter if I put it into this cauldron. My father will never know the bones from those of a puppy, and the few deaths which may result from administering another kind of oil for the incomparable _ol. can._ are not important in a population which increases so rapidly." In short, I took the first step in crime and brought myself untold sorrow by casting the babe into the cauldron. </div> <div style='height: 75em;'> </div> </div> </div>
The same old issue, .scrollTop(0) not working in Chrome & Safari
The problem is with CSS. In particular, the rules I've included below.
html, body {
overflow-x: hidden;
overflow-y: auto;
}
Though these rules are obviously related to scrollbars, I'm not sure why they are causing the behavior you are observing. But if you remove them, it should solve your problem.
See: http://jsfiddle.net/jNWUm/23/.
scrolltop() is not work smoothly in chrome & safari but work in firefox
You're only using position: absolute
and setting scrollTop
on the element because when position: fixed
is used, if the window width is less than the width of the element, a portion of the element is then hidden, even if you scroll right to try to see it:
http://jsfiddle.net/Hbkdt/11/
A different way to approach this problem is to stick with position: fixed
, and then to remedy the problem of a portion of the element being hidden:
http://jsfiddle.net/thirtydot/Hbkdt/26/
The left
property of the element is on scroll set in a way that makes it appear that horizontal scrolling works as desired:
$(window).scroll(function() {
$(".fixed").css("left", -$(window).scrollLeft() + "px");
});
Since position: fixed
is now being used again, the vertical scrolling is perfectly smooth.
windows.scroll working in chrome but not in safari
You could try scrollTo
window.scrollTo(0, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Lists browsersupport for Safari
$(window).scrollTop() is not working in safari
try
var scrollPos = $("body").scrollTop();
webkit browsers always render window/html scrollTop as zero.
scrollTop does not work in Chrome, nor do suggested workarounds
Maybe you can use window.scroll(x,y);
Why does ScrollTop position not work on mobile Safari?
The reason behind this behavior is laid inside the difference in scrolling implementation between the browsers. For example Chrome calculates page scrolling based on the <html>
, while Safari does the same on the <body>
.
Chrome:
Safari:
Considering this info it would reasonable to assume that in Safari document.documentElement
is completely unaware of page global scrolling value.
And to fix this issue you could define a helper func that uses document.scrollingElement
with fallback to getBoundingClientRect
on document.documentElement
:
function getScrollingElement() {
if (document.scrollingElement) {
return document.scrollingElement;
}
const docElement = document.documentElement;
const docElementRect = docElement.getBoundingClientRect();
return {
scrollHeight: Math.ceil(docElementRect.height),
scrollTop: Math.abs(docElementRect.top)
}
}
and use it in your update
func:
function update() {
// ensure initialization and prevent recursive call
if (!logos) init(true);
//*************************************************
/**************************************************
THIS LINE MUST BE HERE.
**************************************************/
let maxScrollDist = getScrollingElement().scrollHeight - viewportHeight;
//*************************************************
let currentScrollPos = getScrollingElement().scrollTop;
// ...
}
function getScrollingElement() {
// ...
}
Full code:
// logo positioning
let logos, logoHeight, barTopMargin;let viewportHeight;
window.addEventListener('load', init);window.addEventListener('resize', setSizes);document.addEventListener('scroll', update);
function init(lockUpdate) { logos = document.querySelectorAll('.scroll-text'); setSizes(lockUpdate);}
function update() { // ensure initialization and prevent recursive call if (!logos) init(true); //*************************************************
/************************************************** THIS LINE MUST BE HERE. **************************************************/ let maxScrollDist = getScrollingElement().scrollHeight - viewportHeight; //*************************************************
let currentScrollPos = getScrollingElement().scrollTop; let newTop;
let middle = currentScrollPos + viewportHeight/2; let middleY = maxScrollDist/2;
if (middle >= (maxScrollDist+viewportHeight)/2) { let p = (middleY - Math.floor(middle - (maxScrollDist+viewportHeight)/2))*100/middleY;
newTop = viewportHeight/2 - logoHeight/2; newTop += (100-p)*(viewportHeight/2)/100; newTop -= (100-p)*(barTopMargin +logoHeight/2)/100; newTop = Math.max(newTop, viewportHeight/2 - logoHeight/2); /*fix*/ } else { let p = (middleY - Math.floor(-middle + (maxScrollDist+viewportHeight)/2))*100/middleY; newTop = barTopMargin*(100-p)/100+(viewportHeight/2 - (logoHeight/2)*p/100 )*p/100; newTop = Math.min(newTop, viewportHeight/2 - logoHeight/2); /*fix*/ }
logos.forEach(function(el) { el.style.top = newTop + "px"; });}
function getScrollingElement() { if (document.scrollingElement) { return document.scrollingElement; }
const docElement = document.documentElement; const docElementRect = docElement.getBoundingClientRect();
return { scrollHeight: Math.ceil(docElementRect.height), scrollTop: Math.abs(docElementRect.top) }}
function setSizes(lockUpdate) { logoHeight = logos[0].offsetHeight; barTopMargin = parseInt(getComputedStyle(document.querySelector('#page'), '::before').top); viewportHeight = window.innerHeight; if (lockUpdate === true) return; update();}
Related Topics
Convert Array of Strings into an Array of Objects
Differencebetween Compile and Link Function in Angularjs
Access JavaScript Property Case-Insensitively
How to Improve Performance of Ngrepeat Over a Huge Dataset (Angular.Js)
Using Socket.Io in Express 4 and Express-Generator's /Bin/Www
Detect Blocked Popup in Chrome
Download a Div in a HTML Page as PDF Using JavaScript
How to Create an Object from an Array of Key-Value Pairs
Multiple, Sequential Fetch() Promise
Jquery Beforeunload When Closing (Not Leaving) the Page
Get Element at Specified Position - JavaScript
Setting Innerhtml VS. Setting Value with JavaScript
How to Show Modal Window in Controller's Action
Combined Comparison/"Spaceship" Operator (<=>) in JavaScript
What Is Right Way to Do API Call in React Js
Setting a Variable to Get Return from Call Back Function Using Promise