You can use jQuery special events to fully pack everything and optimize things in the process. The combination of mousedown and mousemove is also commonly called drag, so here is an example of creating a drag event that you can snap to elements. Please note that this code is specific to jQuery 1.4.2
One advantage of using this is that you only attach the mousemove , mouseout and mousedown handlers after each element, regardless of how many times this element is bound to the drag event. Now this is not the best way to do this, and you can configure only 3 document handlers and manage everything that is equally easily connected with the special events API. It just provides a well-packaged way to create complex interactions than is possible with just your own events or custom events in the jQuery sense.
$("..").bind("drag", function() { ... });
I will try to add additional documentation about what is actually happening, as it looks rather unintuitive, I must admit. Make another nice article on this topic.
See an example of this here . To create this special event, use:
jQuery.event.special.drag = { // invoked each time we bind drag to an element add: function(obj) { var originalHandler = obj.handler; obj.handler = function(event) { var el = jQuery(this); if(el.data('mousePressed')) { return originalHandler.apply(this, arguments); } }; }, // invoked only the first time drag is bound per element setup: function(data, namespaces) { var el = jQuery(this); el.data('mousePressed', false); el.bind('mousedown', function() { jQuery(this).data('mousePressed', true); }); jQuery(document).bind('mouseup', function() { el.data('mousePressed', false); }); el.bind('mousemove', jQuery.event.special.drag.handler); }, // invoked when all drag events are removed from element teardown: function(namespaces) { var el = jQuery(this); jQuery.removeData(this, 'mousePressed'); el.unbind('mousedown'); el.unbind('mouseup'); }, // our wrapper event is bound to "mousemove" and not "bind" // change event type, so all attached drag handlers are fired handler: function(event) { event.type = 'drag'; jQuery.event.handle.apply(this, arguments); } };
source share