Search code examples
javascripthtmlcssscrolldrag-and-drop

How to change the auto scroll "start zone" while dragging in javascript?


I made a project for my students, where they have to drag and drop words into correct boxes. Unfortunately, there are to many questions, so the student needs to scroll to acces the bottom questions. My problem is the following : the task of dragging and moving the mouse to the bottom of the page in order to scroll is really not optimal. The zone where the page starts to scroll is ridiculously small, so I search a way to make it bigger (or to trigger a scroll when the drag is 2/3 of the page).

I am not really good in javascript and css, so please help me.


Solution

  • I did this for you. I hope I understood the task correctly.

    Grab a word and then place it in the orange box. You can rearrange the words after the clamps are placed in the box.

    The words you want to use must be entered in the wordsList variable

    (In the code I have marked with a comment the line that makes the scrolling to the element ID that you need)

    I hope I've been helpful and the children you teach to enjoy what you want to surprise them with

    var wordsList = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'omnis', 'laudantium', 'illo', 'ducimus', 'ipsam', 'eaque', 'quia', 'sequi', 'dicta', 'accusamus', 'ad', 'facilis', 'nam', 'corrupti', 'reiciendis', 'labore', 'aliquam', 'Autem', 'sunt', 'consequuntur', 'officia', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'omnis', 'laudantium', 'illo', 'ducimus', 'ipsam', 'eaque', 'quia', 'sequi', 'ad', 'facilis', 'nam', 'corrupti', 'reiciendis', 'labore', 'aliquam!', 'Autem', 'sunt', 'consequuntur', 'officia'];
    
    var x = document.getElementById('words-wrap');
    for (var i = 0; i < wordsList.length; i++) {
        x.innerHTML += '<span class="myword" id=w' + i + ' draggable="true" ondragstart="drag(event)">' + wordsList[i] + '</span>';
    }
    
    /////////////////
    
    function allowDrop(ev) {
        ev.preventDefault();
    }
    
    function drag(ev) {
        document.location = '#stage'  // <--- Scrolling to element '#stage'
        ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
    .myword {
        display: inline-block;
        margin: 5px;
        cursor: move;
    
        cursor: grab;
        cursor: -moz-grab;
        cursor: -webkit-grab;
    }
    
    #stage {
        border: 10px solid orange;
        min-height: 100px;
    }
    <div id="words-wrap">
    </div>
    
    <div id="stage" ondrop="drop(event)" ondragover="allowDrop(event)">
    </div>