How to recognize the vertical direction of a finger moving up or down on mobile devices when scrolling a page using javascript (Jquery)? Methods based on scroll events, unfortunately, do not work correctly when hiding and showing blocks. I need a touch based method. The code below works only partly for some reason at the second touch of the screen:

$(window).on('touchstart', function(e){ var touchobj = e.changedTouches[0]; // первая точка прикосновения starty = parseInt(touchobj.clientY); // положение точки касания по y, относительно левого края браузера e.preventDefault(); $(window).on('touchmove', function(event){ var touchobj = event.changedTouches[0]; // первая точка прикосновения для данного события var dist = parseInt(touchobj.clientY) - starty; if(dist>0){ jQuery('#btn_mobile').css('opacity', '1'); jQuery('#btn_mobile').css('z-index', '9999'); } else{ jQuery('#btn_mobile').css('opacity', '0'); jQuery('#btn_mobile').css('z-index', '0'); } e.preventDefault(); }, false); }, false); 

1 answer 1

  • on the touchstart set the variable to true
  • on touchmove , IF changing true , we do everything we need
  • on touchend set the variable to false

To determine the direction, in the touchstart save the coordinates of the beginning of the movement, and in the touchmove we calculate relative to them

 let event = null; document.addEventListener("touchstart", function (e) { event = e; }); document.addEventListener("touchmove", function (e) { if (event) { console.log("Move delta: " + (e.touches[0].pageY - event.touches[0].pageY)) } }); document.addEventListener("touched", function (e) { event = null; }); 

Here is an analogue for mousemove, just so that they can look right here):

 var event = null; document.addEventListener("mousedown", function (e) { event = e; }); document.addEventListener("mousemove", function (e) { if (event) { console.log("Move delta: " + (e.screenY - event.screenY)) } }); document.addEventListener("mouseup", function (e) { event = null; }); 

  • one
    The variable will not be visible outside the touchstart function and then I need to determine the direction - Artur Han
  • If you declare a variable in the global space, everything will be visible @ artur-han - Nikita Umnov
  • And the direction still does not determine your way - Artur Han Nov.
  • Updated the answer. In this way, I myself determine the direction and degree of displacement - Nikita Umnov 2:21