Search code examples
javascriptjqueryajaxeventsswipe

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>

Solution

  • 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.