6

I want users to be able to click on an element and also highlight the same element. If they click it should behave like a click but if they mousedown and select some text it should not behave like a click (since that is not a click). jQuery fires a click if you mousedown and then 1 million years later mouse up. I realize you can do:

$myElm.on("mousedown.tmp", function () {
    $myElm.off("mouTsedown.tmp");
    $myElm.on("mouseup", function () {
        $myElm.off("mouseup.tmp")
    }
    }); // 

correct for spelling and factor in other event handlers. i mean roughly speaking.

I don't want to use a plugin.

2
  • Could you not just check in your click handler if there is text within the element selected and return false; ? Commented Oct 16, 2013 at 3:38
  • For some situations that would work. For me if the time between mousedown and mouseup is < 500ms it should be a click. Otherwise its not a click and the user can select/copy the text inside the element. Commented Oct 16, 2013 at 15:02

3 Answers 3

4

Here's my fiddle solution, I hope it's what your looking for.

I'm using mouseup() for the highlighting of the text. And in the click event I'm checking to see if text has been selected.

 var selection = window.getSelection();
      if(selection == 0)
       // Click event code goes here

Below is the code.

$(function(){
  $("div").click(function(){

      var selection = window.getSelection();
      if(selection == 0)
      {
          // click event code goes here.
      }
  });
  $("div").mouseup(function(){
    document.execCommand("BackColor", false, "yellow"); // highlight selected text
      document.designMode = "off";
  });    
  $("div").mousedown(function(){
     document.designMode = "on"; // Turn on design mode
  });
 });
Sign up to request clarification or add additional context in comments.

1 Comment

About the selection == 0 condition. window.getSelection(); function will always return an object indicating the range of text selected by the user even when there is nothing selected. So instead you could check selection.type === 'Caret', which is a click event type when there is no selection.
1
var mydate = new Date()
var downtime;

$('#div').on('mousedown', function() {
    downtime = mydate.getTime();
});

$('#div').on('mouseup', function() {
    if((mydate.getTime() - downtime) < 500) {
        //perform click function 
    }
    else {
        //highlight text
    }
});

Comments

0

Keep track of the mouse position on mousedown. Compare it with the mouse position on mouseup. If the mouse has moved a certain number of pixels, prevent the default event.

event.preventDefault();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.