Search code examples
jquerycenteringscrolltogsap

ScrollTo.js: scroll to the exact center of a div


I am trying to figure out the jquery to scroll the exact center of a div when you click a button. At present I can only scroll to the X and Y coordinate with a declared offset. This would mean I would have to redeclare the X and Y in jquery depending on what device you are using (large monitor, laptop, ipad, iphone), and it won't be exactly in the center either.

I know it has to do with declaring vars of window height and window width divided by 2 but am struggling to make it work using answers on SO.

var wWidth = $(window).width();
var wHeight = $(window).height();

Codepen: https://codepen.io/artchibald/pen/ddKVNw

Thanks.


Solution

  • You're right about using half the width and height of the div. So it could become:

    clickmeVar.onclick = function() {
    TweenLite.to(window, 1, {scrollTo:{y:"#myDiv", offsetY: $(window).innerHeight() / 2 - $('#myDiv').height() / 2, x:"#myDiv", offsetX: $(window).innerWidth() / 2 - $('#myDiv').width() / 2, autoKill:false}},100);
    };
    

    Or without jQuery selectors:

    clickmeVar.onclick = function() {
    TweenLite.to(window, 1, {scrollTo:{y:"#myDiv", offsetY: window.innerHeight / 2 - document.querySelector('#myDiv').clientHeight / 2, x:"#myDiv", offsetX: window.innerWidth / 2 - document.querySelector('#myDiv').clientWidth / 2, autoKill:false}},100);
    };
    

    Here we're using half the visible screens width and height, minus half the width and height of the element.

    Here's a working example:

    var clickmeVar = document.getElementById("clickme");
    var windowheight = $(window).height();
    var windowwidth = $(window).width();
    var pagecenterW = windowwidth/2;
    pagecenterW=pagecenterW/2;
    var pagecenterH = windowheight/2;
    pagecenterH=pagecenterH/2;
    
    clickmeVar.onclick = function() {
    TweenLite.to(window, 1, {scrollTo:{y:"#myDiv", offsetY: $(window).innerHeight() / 2 - $('#myDiv').height() / 2, x:"#myDiv", offsetX: $(window).innerWidth() / 2 - $('#myDiv').width() / 2, autoKill:false}},100);
    };
    //      $("#myDiv")
    //      .css({top: pagecenterH + 'px', left: pagecenterW+ 'px'});
    body {
      width: 3000px;
      height:2000px;
      background:blue;
    }
    #myDiv {
      width:100px;
      height:100px;
      background:red;
      position:relative;
      left:800px;
      top:1000px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
    <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/ScrollToPlugin-latest-beta.js"></script>
    
    <button id="clickme">click here to put the red square exactly in the center of the viewport</button>
    <div id="myDiv"></div>