Search code examples
javascripthtmlcssreactjsdrag

HTML Horizontal draggable DIV


Im pretty new to html/css and currently trying to make an horizontal draggable slider for an Smartphone-Webapp.

Basically want i am searching for are three divs in a horizontal line, where div 1 and 3 are out of view. If im dragging div 2 to left or right, 1 or 3 should appear.

Im creating my app with react and got already the div 2 to be draggable via an library.


Solution

  • First, make a parent div and add three divs to it. Stack the divs next to each other and for parent div add overflow-x: scroll. Each child should have a width and height to that of the screen. For that add min-width: 100vw; and min-height: 100vh;.

    Now, to display the central div, the scrollbar of the div has to be moved.

    parent.scrollLeft += document.querySelector(".C1").clientWidth; This will position the scrollbar to the center. Essentially, it will move the scroll bar by the width of the screen.

    Scroll down when you run the snippet to see the horizontal scrollbar.

    var parent = document.getElementById("Parent");
    parent.scrollLeft += document.querySelector(".C1").clientWidth;
    * {
        margin: 0px;
        padding: 0px;
    }
    
    #Parent {
        overflow-x: scroll;
        display: flex;   
    }
    
    .C1, .C2, .C3 {
        min-width: 100vw;
        min-height: 100vh;
    }
    
    .C1 {
        background-color: red;    
    }
    
    .C2 {
        background-color: green;    
    }
    
    .C3 {
        background-color: blue;    
    }
    <div id="Parent">
        <div class="C1">
        </div>
        <div class="C2">
        </div>
        <div class="C3">
        </div>
    </div>