0

I have researched a lot but couldn't find a proper solution for my problem.

I have found "https://api.jquery.com/scrollleft/" and "https://www.w3schools.com/jsref/met_win_scrollto.asp" but I don't really understand how I can set them up properly that it just centers the view of my whole website, which is normally wider than the browser-size.

I would like to have something like this:

<script>
window.scrollTo(50%, 0);
</script>

Just an "easy" centeration of my view-point and nothing more. Can you please setup the according script for doing this?

  • Get the width in pixels using https://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code – Paul Abbott Jun 09 '17 at 16:08

1 Answers1

0

Here's a simple but effective solution, it gets the mid point of the document by getting the scroll width which is the width of the whole of the document. It works out the midpoint by dividing by 2. We then have to do the method which you stated in your original post. window.scrollTo(mid, 0);

var body = document.body;
var width = document.body.scrollWidth;
var mid = width / 2;
var trigger = document.querySelector('#scroll');

trigger.addEventListener('click', function() {
    window.scrollTo(mid, 0);
});

console.log(mid);
<div style="width: 7000px;"><button id="scroll">Scroll</button></div>
  • The div is only there to set the width of the document for the example, if you want to do this without a button click just take the `window.scrollTo(mid, 0);` out of the button click event. –  Jun 09 '17 at 16:25
  • Thanks so far! Unfortunately something is not working on my side when I try to implement this script into unbounce. I guess I have to put it in the header, right? When I click it, just nothing happens.... What could I have forgotten? – Peter Mueller Jun 09 '17 at 16:30
  • Do you have a button with the id of `scroll` ? –  Jun 09 '17 at 16:31
  • And what happens when you click the button? Is anything in the browser log? –  Jun 09 '17 at 16:32