0

How to manage touch events. When I write a few touchstarts on different elements they are all activated at the same time and I can't separate them. Can you please help me to understand how to manage them right without a third-party libraries . I would be grateful for a hint or small tutorial if it exists.

$(".content").on("touchstart", function(){$(this).stop().animate({top: '-50px'}, 600);});
Andrii
  • 57
  • 4
  • 11
  • can't get your question actually. Do you have issues with parent/child touch events. – Jai Aug 28 '15 at 11:40
  • I can't reach the elements. For example, these two functions are rerformed simultaneously, although they are determined for different elemets. `$('.main').on('touchstart', function() { $('.main').stop().animate({top: '0px'}, 600, 'easeOutBounce'); });` second events `$('.content').on('touchstart', function() { $('.content').stop().animate({top: '-50px'}, 600, 'easeOutBounce'); });` – Andrii Aug 28 '15 at 11:53
  • so my guess: `.main` is the container which holds/contains `.content` right. – Jai Aug 28 '15 at 12:04
  • Yes, .content inside .main `
    `
    – Andrii Aug 28 '15 at 12:06

1 Answers1

1

As per your issue seems to be a event is bubbling up at the dom tree. What it means if you fire any event which is bound on child element and same event is also applied on parent then any event which occurs on child will climb up to the parent and that also executes the same.

so i suggest you to use event.stopPropagation(); and pass the event in callback function:

$('.main').on('touchstart', function() { 
     $('.main').stop().animate({top: '0px'}, 600, 'easeOutBounce'); 
}); 

$('.content').on('touchstart', function(event) { 
    event.stopPropagation();
    $('.content').stop().animate({top: '-50px'}, 600, 'easeOutBounce'); 
});

look at the demo below, using click event.

$('.main').click(function(){
    alert(this.className + ' clicked.');
});

$('.content').click(function(event){
    //event.stopPropagation();
    alert(this.className + ' clicked.');
});


// you can enable the commented line and see the effect.
.main{border:solid 1px green; padding:20px;}
.content{border:solid 1px red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main"> parent<br><br><div class="content">child</div> </div>
Jai
  • 74,255
  • 12
  • 74
  • 103