2

I'm building Facebook like reactions system in HTML/CSS/JS. I'm trying to achieve simmilar touch effect as it is on Facebook for mobile users. So I want to allow users to select reaction by sliding the finger between reactions and react when they will release on desired reaction. For that I'm using touchstart, touchmove and touchend event. The problem is that I want to detect when the user will slide the finger out the reaction to restart touchmove event for the next reaction. I was able to detect that, but not able to restart touchmove event as it results in error Uncaught TypeError: Cannot read property 'touches' of undefined. So the final effect should be that when user starts touch on "Like" and slides finger on "Haha" and releases on it, it should react on "Haha" instead of "Like".

Here's my HTML:

<div class="reactions">
    <div class="reactions_item -like">Like</div>
    <div class="reactions_item -love">Love</div>
    <div class="reactions_item -care">Care</div>
    <div class="reactions_item -haha">Haha</div>
    <div class="reactions_item -wow">Wow</div>
    <div class="reactions_item -sad">Sad</div>
    <div class="reactions_item -angry">Angry</div>
</div>

Here's my JS

var reaction = jQuery('.reactions_item');
var touchOffset;

reaction.on('touchstart', function(e) {
   e.preventDefault();
   var touchEvent = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
   touchOffset = document.elementFromPoint(touchEvent.pageX,touchEvent.pageY);
   console.log('touch started');
});

reaction.on('touchmove', function(e) {
    e.preventDefault();
    var touchEvent = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
    if (touchOffset !== document.elementFromPoint(touchEvent.pageX,touchEvent.pageY)) {
        reaction.off('touchmove');
        reaction.trigger('touchmove');
        console.log('finger is out of current element and should restart touchmove for next element');
    }
});

reaction.on('click tap touchend', function(e) {
    console.log('touch released and should react');
});
Jon Code
  • 111
  • 8

1 Answers1

0

I suggest you should use "mousedown" & "mouseup" js events. reference https://api.jquery.com/mousedown/ https://api.jquery.com/mouseup/

for more information please check below link. https://api.jquery.com/category/events/

Waqar Akram
  • 107
  • 5
  • Why should I use "mousedown" & "mouseup" events instead? What is the advantage? I only want that functionality on touch devices. – Jon Code Jun 08 '21 at 12:48
  • Ok well If you want to use "touchmove" & "touchstart" then use like this var reaction = jQuery('.reactions_item'); reaction.addEventListener('touchstart', event => { // touch event started }) – Waqar Akram Jun 08 '21 at 13:56