Estoy desplazando varios DIV .scroll-item dentro de un DIV principal .pathscroll .
Compruebo la posición de desplazamiento y luego cambio la posición del DIV secundario en consecuencia. También se muestra una columna a continuación, según el niño en la ventana gráfica.
Código HTML:
<div class="pathscroll"> <div class="scroll-item" id="1">Montag</div> <div class="scroll-item" id="2">Dienstag</div> <div class="scroll-item" id="3">Mittwoch</div> <div class="scroll-item" id="4">Donnerstag</div> <div class="scroll-item" id="5">Freitag</div> </div>Código JS:
$('body').on('touchend', '.scroll-item', function() { var scrollitem = $(this); // determine most visible scrollitem $('.scroll-item').each( function() { let scrollpos_left = ($(this).offset().left + 100); if (scrollpos_left>0 && scrollpos_left<320) { scrollitem = $(this); } }); $('.pathscroll').animate({ // get scroll position and position of element to the left, then scroll the distance scrollLeft: $('.pathscroll').scrollLeft() + scrollitem.offset().left - $('.pathscroll').offset().left - 2, }, 200); // show the column accordingly var pathid = scrollitem.attr('id'); if ( $('#"'+pathid+'"]:visible').length == 0) { $('.path-column').hide(150); $('#'+pathid).show(150); } }); Puede ver el problema en la grabación del GIF: cuando el usuario se desplaza con un "swing", el DIV aún se desplaza, pero el touchend se activa demasiado pronto , lo que genera un comportamiento extraño.
¿Cómo puedo verificar si el DIV todavía se está desplazando y solo luego activar el evento touchend u omitir el evento y simplemente buscar un evento de "fin de desplazamiento"?
Actualizar:
Descubrí cómo detectar el desplazamiento del DIV principal por:
var scrollpos_last = 0; var scrolling_left = false; $('.pathscroll').scroll( function() { let scrollpos_now = $(this).scrollLeft(); scrolling_left = (scrollpos_now < scrollpos_last); scrollpos_last = scrollpos_now; });¡¿Tal vez pueda activar el evento touchend después del final del pergamino?! Pero no hay un evento "scrollend" como parece.
Solución, gracias @Kosh.
Código JS:
// Jquery extension (event debouncing), https://stackoverflow.com/a/3701328/1066234 $.fn.scrollEnd = function(callback, timeout) { $(this).on('scroll', function() { var $this = $(this); if ($this.data('scrollTimeout')) { clearTimeout($this.data('scrollTimeout')); } $this.data('scrollTimeout', setTimeout(callback, timeout)); }); }; $('.pathscroll').scrollEnd(function() { set_path_scroll_item(); }, 100); Y set_path_scroll_item(); contiene el código anterior en la pregunta.