Search code examples
javascriptjqueryeventtrigger

Stop Trigger function to run multiple times in Jquery


for some reason my trigger function (even when is called once) runs the trigger multiple times.

Here is the code:-

$('.video-section ul li a').on({ 'touchstart' : function(){ 

    console.log("Touched"); 
    $(".video-section ul li a").trigger("click");

} });

$(".video-section ul li a").click(function(e){

  e.preventDefault();

  console.log("clicked");
  e.stopPropagation();

});

What happens is that the "click" function is run multiple times when it's triggered once by the "touch" function.

Any way, I can force it to run once?

Thanks.


Solution

  • click gets fired 300ms after you touch the element whether you trigger it or not on the touchstart. So, because you trigger it on touchstart, it fires twice. You could do something like:

    Example here: JS Fiddle

    $('.video-section ul li a').on('click touchstart', function(e){ 
        e.preventDefault();
    
        if(e.type == "touchstart") {
           console.log("touchstart event");
           // whatever else on touch event
        } else if(e.type == "click") {
           console.log("click event");
           // whatever else on click event
        }
    
    });