user1015214
user1015214

Reputation: 3081

How to bind multiple sequential events in jQuery?

I want to be able to bind multiple sequential events using jquery. I want to do the following:

Click on div1 - aka mousedown event - now, IF you start moving the mouse while you are STILL pressing down on the mouse, THEN do some function.

What's the smoothest way of doing this? Just to put an if inside of a .on() call, or is there something simpler?

Upvotes: 4

Views: 625

Answers (1)

Alexander
Alexander

Reputation: 23537

You can make use of .on() and .off() to achieve this.

var $div = $("div");

var mousemove = function() { ... };

$div.on({
  mousedown: function() {
    $div.on("mousemove", mousemove);
  },
  mouseup: function() {
    $div.off("mousemove", mousemove);
  }
});​

Notice that .on() and .off() are the recommended methods to bind and unbind events respectively.

You can check a live example.


UPDATE

Alternatively, you can bind the mouseup event to the document. This way you can detect the release of the mouse even if it doesn't occur while hovering your element.

var $document = $(document);
var $div = $("div");

var mousemove = function() { ... };

$div.mousedown(function() {
  $div.on("mousemove", mousemove);
})

$document.mouseup(function() {
  $div.off("mousemove", mousemove);
});​

Also, a shorthand function for it. Let's call it .drag().

$.fn.drag = function(fn) {
  var $document = $(document);
  return $(this).each(function() {
    var self = this;
    var $this = $(this);
    var mousemove = function() {
      fn.dragging && fn.dragging.call($this);
    };
    $this.mousedown(function() {
      fn.start && fn.start.call($this);
      fn.dragging && $this.on("mousemove", mousemove);
    });
    $document.mouseup(function() {
      fn.dragging && $this.off("mousemove", mousemove);
      fn.stop && fn.stop.call(self);
    });
  });
};

$("div").drag({
  start: function() { ... },
  dragging: function() { ... },
  stop: function() { ... }
});​

You can see it live here.

Upvotes: 5

Related Questions