1

I'm trying to adapt the code from this answer to a jQuery appended element, without using any "flag" variables.

Original code is :

$(window).mousedown(function(e) {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
        alert('mousedown > 2 sec');   
    }, 2000); 
}).mouseup(function(e) {
    clearTimeout(this.downTimer); 
});​

So I can't see how to use it with document :

$(document).on('mousedown', '.item', function(){
// How to chain mouseup ? 
});

I've tried with

$(document).find('.item')

but no luck.

Community
  • 1
  • 1
kursus
  • 1,396
  • 3
  • 19
  • 35

2 Answers2

2

This can't be done using chaining, because .on() returns the object it was called on, and that doesn't include the selector that it delegates to.

Instead, you can put the event bindings in an object.

$(document).on({
    mousedown: function() { ... },
    mouseup: function() { ... }
}, '.item');
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Unless I'm misunderstanding the question, this snippet is a working example of mousedown/mouseup timer delegation via chained event handlers. The chaining works on the document element, not on the delegated descendant, but the end result seems to match up with the behavior you're looking for.

Here, this is the filtered the descendant element that is actually the event target.

$(document)
  .on('mousedown', '.has_timer', function() {
    clearTimeout(this.downTimer);
    $('#this_identity').text(this.className);
    this.downTimer = setTimeout(function() {
      alert('mousedown > 2 sec');
    }, 2000);
  })
  .on('mouseup', '.has_timer', function() {
     clearTimeout(this.downTimer);
  });
.has_timer {
  border: 1px solid green;
  margin: 1em;
  padding: 1em;
}
.no_timer {
  border: 1px solid blue;
  margin: 1em;
  padding: 1em;
}
.this_test {
  border: 1px solid gray;
  margin: 1em;
  padding: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="has_timer first_has_timer">This element has a mousedown timer.</div>
<div class="no_timer">This element does not have a timer.</div>
<div class="has_timer other_has_timer">This other element has a mousedown timer.</div>
<div class="no_timer">This other element does not have a timer.</div>
<div class="this_test">"this" className: <span id="this_identity"></span></div>
twernt
  • 20,271
  • 5
  • 32
  • 41