TouchSwipe – Implement delegated swipe event for inner elements

In the previous post, we attach the swipe event listener directly on the #box element.

 

How about if your target elements is dynamically added to the DOM? In that case, the event listener would not work for the newly inserted inner elements. A work around is attached the event listener to the parent element instead. Here is another example for the delegated event implementation of TouchSwipe.

<!doctype html>
<html>
<head>
  <title>Eureka! - TouchSwipe Example</title>
  <style type="text/css">
    .box {
      background-color: green;
      width: 400px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      list-style: none;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <ul id="boxes">
    <li class="box">Old box</li>
    <li class="box">Old box</li>
    <li class="box">Old box</li>
  </ul>
  <button id="add">Add box</button>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="js/jquery.touchSwipe.min.js"></script>
  <script type="text/javascript">
    $("#add").click(function(){
      $("#boxes").append('<li class="box">New box</li>');
    });

    $("#boxes").on('mouseover','.box', function() {
      $(this).trigger('swiping');
    });

    $("#boxes").on('swiping','.box', function() {
      var $this = $(this);
      $this.swipe({
        swipe: function(event, direction, distance, duration, fingerCount) {
          $this.text("You swiped " + direction );
        }
      });  
    });
  </script>
</body>
</html>

 

Done =)

Reference:

Advertisement

4 thoughts on “TouchSwipe – Implement delegated swipe event for inner elements”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.