Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click() is triggering when selecting/highlighting text

I have a <div> with a bunch of text in it. This <div> also has a .click() event on it using jQuery.

The problem I'm having is that the .click() is being triggered when selecting/highlighting text. Even holding the mouse down for several seconds before releasing.

Here is a JSFiddle that shows the issue: http://jsfiddle.net/ym5JX/

The behavior that I would expect is that highlighting text isn't the same as clicking on the element.

like image 524
krische Avatar asked Apr 30 '12 20:04

krische


People also ask

What event occurs when user highlights text in text field?

The onselect event occurs after some text has been selected in an element. The onselect event is mostly used on <input type="text"> or <textarea> elements.

How do you highlight a word in jquery?

Usage example: // Highlight "keyword" in the specified context $(". context"). mark("keyword"); // Highlight the custom regular expression in the specified context $(".

How do you highlight text in JavaScript?

Highlight Text Using the Mark Tag Method in JavaScriptIf you surround any text inside the mark tag, the browser will automatically highlight it in a striking yellow color. This will make highlighting a searched text quite a simple task then.


2 Answers

That's because a click is a mousedown followed by a mouseup. My suggestion is to check getSelection inside the click handler. If it's set, then you selected something, else you just clicked.

$('#click').click(function() {     var sel = getSelection().toString();     if(!sel){         alert("clicked");     } });​ 

DEMO: http://jsfiddle.net/ym5JX/3/

like image 102
Rocket Hazmat Avatar answered Sep 26 '22 10:09

Rocket Hazmat


As I posted on comment, mosuedown + mouseup = click which is exactly what highlighting does. There is workaround for this.. see below,

var isClick = 0; $('#click').click(function() {     if (isClick == 1) {         alert("clicked");     } }).mousedown(function () {     isClick = 1; }).mousemove(function () {     isClick = 0; }); 

DEMO

like image 33
Selvakumar Arumugam Avatar answered Sep 22 '22 10:09

Selvakumar Arumugam