简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM