Andrii
Andrii

Reputation: 57

jQuery touch events

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);});

Upvotes: 0

Views: 6196

Answers (1)

Jai
Jai

Reputation: 74738

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>

Upvotes: 1

Related Questions