Reputation: 5201
On my HTML page there is an element with some text on it. I assigned an action to take place when that element is clicked. When the users click the element many times in a row, sometimes a double-click occurs, which causes the text to be selected (highlighted), thus damaging the appearance. I tried to prevent it using a dummy event handler that prevents the default behaviour of the double-click (dblclick) event. However, this doesn't seem to work. It seems the text is selected and highlighted before my dummy event handler is even executed.
function doNothing(event) {
alert('doNothing'); // Added for debugging. The alert is shown, meaning the event handler is invoked. When I get the alert, the text is already highlighted.
if(!event) event = window.event;
if(event.preventDefault) event.preventDefault();
event.cancelBubble = true;
if(event.stopPropagation) event.stopPropagation();
return false;
}
myElem.onlick = doSomething; // This is the event for a single click. Works well.
myElem.ondblclick = doNothing; // The event handler is called, but the text is already highlighted.
Specific questions:
1) Has what I'm after got anything to do with the double-click event at all? (As I see the text is already highlighted when the alarm is fired, I suspect maybe it's another mechanism. I suspected the default behaviour for the (single) click event might have had something to do with it, but I cancelled the default behaviour for the (single) click event as well.)
2) If it's not got to do with the dblclick event, what's it got to do with then? How do I prevent it?
3) If it is about the dblclick event, am I doing something wrong? (BTW, I guess using all of preventDefault()
and cancelBubble = true
and stopPropagation()
and return false
is an overkill. What's the minimum code I need in order to prevent the default behaviour?)
4) Any other idea how to get the desired outcome (double-clicking not selecting and highlighting the text)?
I'm testing with FF 11 (but eventually need a cross-browser solution).
Thanks!
Upvotes: 5
Views: 5091
Reputation: 4652
Had same issue and right away I added event.preventDefault() in dblclick handler and it didn't help. What I didn't account for was event bubbling and the fact that default behavior was triggered in child element before it was triggered in parent element.
If there's a parent with multiple children, you still need text to be selectable in it but don't want the selection to happen on double click, there're 2 options:
Upvotes: 1
Reputation: 32066
myElem.onmousedown = function(e) {
e.preventDefault()
}
edit: changed it from return fasle to e.preventDefault, which will still allow the click event to fire.
Upvotes: 4