How to detect a click but not drag using jQuery?

I have code that selects text when the user clicks the p tag, but I don't want to do this when the user selects the text inside. Is it possible to detect a click, but without dragging?

I have a simple code:

 $('.conteiner').on('click', 'p.xxx', function() { $(this).selection(); }); 

But the click is executed even if I drag between mousedown and mouseup. Selection is a plugin that selects text using getSelection or Rage.

+8
javascript jquery javascript-events mouseevent
source share
2 answers

Similar to this: Can you detect drag and drop? in jQuery?

You can use mousedown and mouseup to determine if there is a drag.

  $(function() { var isDragging = false; $(".conteiner") .mousedown(function() { $(window).mousemove(function() { isDragging = true; $(window).unbind("mousemove"); }); }) .mouseup(function() { var wasDragging = isDragging; isDragging = false; $(window).unbind("mousemove"); if (!wasDragging) { $(this).selection(); } }); }); 

Here is the demon plunker: http://embed.plnkr.co/Y7mrOP/

+11
source share

Found a better way since I need to detect drag and drop to select text that works better:

 var get_selected_text = (function() { if (window.getSelection || document.getSelection) { return function() { var selection = (window.getSelection || document.getSelection)(); if (selection.text) { return selection.text; } else { return selection.toString(); } }; } else if (document.selection && document.selection.type !== "Control") { return function() { return document.selection.createRange().text; }; } return function() { return ''; }; })(); self.mouseup(function() { if (get_selected_text() === '') { // click not drag } }); 
0
source share

All Articles