Search code examples
javascripthtmlcss

Expand/Resize a div with JavaScript Touch Events


function touchEvtResize() {
    var block = document.getElementsByClassName("top-three-quarters"),
        slider = document.getElementsByClassName("slider");

    slider.addEventListener('touchstart', function (e) {
        let dragY = e.clientY;

        document.addEventListener('touchmove', function (e) {
            block.style.height = block.offsetHeight + e.clientY - dragY + "px";
            dragY = e.clientY;
        });

        docuemnt.addEventListener('touchend', function (e) { });
    });
}
.top-three-quarters {
    overflow-y: auto;
    resize: vertical;
}

.bottom-quarter {
    flex: 1;
    max-height: 100%;
    min-height: 5%;
}

.slider {
    background-color: #dee2e6;
    cursor: row-resize;
    user-select: none;
    height: 10px;
}
<div class="top-three-quarters">
</div>
<div class="bottom-quarter">
  <div class="slider">
  </div>
</div>

I have this code which works with mouse events. But I would like to make it work with touch events for touchscreens. I have been doing research and have not been able to find anything helpful. I am still new with JS so any guidance is helpful. Preferably no libraries if possible. I have a fiddle of what it looks like with mouse events.

<div class="top-three-quarters">
</div>
<div class="bottom-quarter">
  <div class="slider">
  </div>
</div>
.top-three-quarters {
    overflow-y: auto;
    resize: vertical;
}

.bottom-quarter {
    flex: 1;
    max-height: 100%;
    min-height: 5%;
}

.slider {
    background-color: #dee2e6;
    cursor: row-resize;
    user-select: none;
    height: 10px;
}
    let block = document.querySelector(".top-three-quarters"),
        slider = document.querySelector(".slider");

    slider.onmousedown = function dragMouseDown(e) {
        let dragX = e.clientY;

        document.onmousemove = function onMouseMove(e) {
            block.style.height = block.offsetHeight + e.clientY - dragX + "px";
            dragX = e.clientY;
        }

        document.onmouseup = () => document.onmousemove = document.onmouseup = null;

    }

Fiddle

I have tried similar examples such as Example1 and example2 but no luck. Not asking you guys to code it for me but just some guidance and tips so I can solve it!


Solution

  • I was able to make it work with some blazor. I just did the function in c# and passed the event from blazor to js to avoid touch events in javascript.