Click-and-Hold Trigger Event

Question:

Using jQuery, how can I simulate a click-and-hold event?


I am currently banging my head against the wall and cannot figure out how to do this!

I also tried google searches and forums, but to no avail.

In my current example, I am using jQuery UI .draggable() .

Ideally, I would like to do the following:

  • Click / mousedown on the div .
  • Imitate the click-and-hold event and move the element freely.
  • On the next click / mousedown, complete the click-and-hold event.

When I try to perform functions such as:

 $("#drag").draggable().mousedown(function(e){ e.preventDefault(); return $(this).mousedown(); }); 

Then it causes an endless loop, which will ultimately lead to a browser crash. However, I am not sure how to trigger the .mousedown() persistent event.

Here is a demo of what I have: http://jsfiddle.net/vPruR/16/ .

Any help would be greatly appreciated!

+7
source share
2 answers

I don’t think there is any option to simulate a click and hold. It can also create too much browser dependency.

So, you can try something as shown below.

 var click = false, top = null, left = null; $(document).bind('mousemove', function (e) { if (click == true) { $('#drag').css({ left: e.pageX - left, top: e.pageY - top }); } }); $('#drag').draggable().click(function(e) { top = e.pageY - $('#drag').position().top; left = e.pageX - $('#drag').position().left; click = !click; return false; }); $('html').click(function() { click = false; }); 

DEMO: http://jsfiddle.net/dirtyd77/qbcQn/

+8
source

Wolf and Dom solutions work perfectly and are the basis for my solution, but you mentioned that you are using jquery ui draggable , so this is a possible solution using a jquery ui draggable object in combination with droppable . I am trying to trigger droppable events when draggable drag and drop them and throw them at them, so I used the built-in / private functions of the ui.mouse object, which draggable inherits and overrides.

 $(document).ready(function(){ var click = false $(document).bind('mousemove', function (e) { if (click == true) { $('#drag').data('uiDraggable')._mouseDrag(e); } }); $('#drag').draggable().click(function(e) { if(!click){ $(this).data('uiDraggable')._mouseCapture(e, true) $(this).data('uiDraggable')._mouseStart(e, true, true); }else{ $(this).data('uiDraggable')._mouseUp(e); $(this).data('uiDraggable')._mouseStop(e); } click = !click; return false; }); $('html').click(function() { click = false; }); }); 

Heres a fiddle . To see the dropdown stuff, just uncomment the dropdown stuff in js.

Note: this is a solution for the current version of jQuery ui (1.9.2), but may change in future versions as it uses private calls.

+4
source

All Articles