So I'm trying to get a specific element to be centered on the screen when the page loads. This element is flanked on both sides by an element that is 100% of the window width.
Eventually, there will be more sections and I'd like the user to be able to scroll freely between all of them, though for the purposes of the web app I'm doing, I need to be able to control the scrolling with javascript as well.
Here's a Fiddle to try it out. As you can see, it works fine the fiddle. Now, when I load it on my page, it flashes at the right position, then goes to wherever the browser thought it was last scrolled. If you load the page fresh, then that will be at 0. If you scrolled a little bit to the right, then whatever that variable is, it will take over and scroll the element to that spot instead of the designated spot. Sometimes you can see a flash of where the element is supposed to be, then it goes back to wherever the browser thought you were last.
You can see a live example of it here: http://www.playafterdj.com/index2.php
The simple HTML:
<div class="wrapper">
<section class="fill"></section>
<section class="init"></section>
<section class="fill"></section>
</div>
the CSS:
* {
margin:0;
padding:0;
box-sizing:border-box;
}
html, body {
width:100%;
height:100%;
position:relative;
}
.wrapper {
width:100%;
height:100%;
position:relative;
white-space: nowrap;
}
section {
width: 100%;
max-width: 640px;
height: 100%;
background-color: #313138;
padding: 10px;
margin-right: 20px;
display: inline-block;
vertical-align: top;
}
section.fill {
width: 100%;
max-width:100%;
margin-right: 0;
background-color: transparent;
padding:0;
}
and finally the JS:
$(window).load(function(){
var winW = $(window).width();
var sectionW = $('.init').width();
var startPos = (winW/2)+(sectionW/2)+15;
$('body').scrollLeft(startPos);
});
So, I get the right number with startPos
. In the fiddle, you can test it out by scrolling and seeing that the startPos
matches up with the scrollLeft()
of the body. Unfortunately the browser overrides this. I've tried using these couple of answers with no avail:
Prevent automatic browser scroll on refresh
Disable brower's auto scroll after a page refresh?
Any advice?