Search code examples
javascripthtmlcssdraggable

HTML full size div containing a draggable table


I'm not sure how to explain what I exactly want (which makes it really hard to google for as well), but I would like to create a table with each cell a specific width and height (let's say 40x40 pixels).

This table will be way larger than the viewport, so it would need some scrolling, but I don't want scrollbars (this part ain't a problem), but a way to drag the table around "behind the viewport".

To make it a bit more complex, I need to be able to center a specific cell and know which cell is centered too (although if I know for example that the table is on left: -520px; I can calculate what the situation is).

Long story short, I'm looking for something that looks and works like maps.google.com, but then with a table and cells instead of a canvas or divs.


Solution

  • What you're trying to achieve is relatively simple. You have a container div element with position: relative; overflow: hidden applied via CSS and the content set to position: absolute. For example:

    <div class="wrapper">
        <div class="content-grid">
            ... your grid HTML ...
        </div>
     </div>
    

    You then need to set up some mouse/touch tracking javascript, you can find plenty of examples around Stack Overflow or Google, which monitors the position of the mouse at mousedown or touchstart events and then tests this repeatedly on an interval to see where the pointer is and update the content-grid top and left position, until mouseup or touchend.

    You can make this animation smooth using CSS transition on left and top.

    The tricky bit is calculating the position for the centre cell. For this I would recommend calculating a central zone, the size of your grid cells (i.e. 40x40) in the middle of your container element. Then checking if any grid cell is currently more than 1/4 inside that zone, and treating it as the "central" element.

    Here is a basic example for position a cell within a grid within a wrapper: https://jsfiddle.net/tawt430e/1/

    Hope that helps!