Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding swipe event to dynamically loaded content with jquery

Here is a js fiddle showing the problem.

http://jsfiddle.net/4CLqY/4/

The swipe works fine on the red box but not on the new blue box which is created after pressing the new button. (swipe across red box with mouse for change)

Sorry if this a dupe but I have not found any solution online which solves my particular issue.

The code is from the touchSwipe site

javascript

 $(function() {      
  //Enable swiping...
  $(".test").swipe( {
    //Generic swipe handler for all directions
    swipe:function(event, direction, distance, duration, fingerCount) {
      $(this).text("You swiped " + direction );  
    },
    //Default is 75px, set to 0 for demo so any distance triggers swipe
     threshold:0
  });
});

$(document).on('click','button',function(){


$('<div class="test" id="test2">Swipe me</div>').appendTo('body');

});     

HTML

<div class="test">Swipe me</div>

<button>New</button>
like image 709
chris Avatar asked May 17 '26 02:05

chris


1 Answers

You can reattach the swipe event to the new elements, because they don't exist when you add the initial event.

Try this fiddle.

I added a addSwipeTo function that takes a selector, and adds the event to the elements it matches.

like image 116
nicosantangelo Avatar answered May 19 '26 16:05

nicosantangelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!