0

I've added a mouseup event listener to a span that will increment the value in a sibling text input via js... think of arrow controls that allow a user to click increase or decrease a value. The problem: if a user clicks the span too fast, Safari/Chrome interpret it as a double-click and starts to select nearby items and render them under a blue box. There must be a default behavior in these browsers that auto selects nearby text as a convenience function when you double-click.

I've tried adding a dblclick event to catch the event and run preventDefault(), stopPropagation() or return false. However, nothing works. I've also added -user-select: none; CSS rules to the nearby items. However, the browser just skips over these and finds something else to highlight. Any thoughts on how to prevent this behavior?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vince
  • 589
  • 9
  • 16

2 Answers2

1

In the double click event callback you defined, set the object you want to click as focused. https://developer.mozilla.org/en/DOM/element.focus

Edit: also, try calling focus after a short time rather than immediately.

An alternative is outlined below:

<script type="text/javascript">
    function test() {
        // something
    }
</script>

<style type="text/css">

span::selection,
span *::selection {
    background: transparent;
}
span {
    -moz-user-select: none;
    -khtml-user-select: none;
}

</style>

<span>surrounding text <a href="#" onclick="test(); return false;">Link</a> more text</span>

Double clicking a hyperlink doesn't cause surrounding text to be selected. Also, please see this question for js functions that remove selection:

Prevent text selection after double click

Community
  • 1
  • 1
Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
  • Nice. This works. Thanks. For me, the minimum timeout is 500ms. So there's still a blue flash around nearby objects. But that's better than a full blue overlay. – Vince Aug 16 '11 at 17:38
  • I found another solution that's working well so far... http://bytes.com/topic/javascript/answers/635488-prevent-text-selection-after-double-click – Vince Nov 04 '11 at 16:05
0

After finding the link in the comment above, I was able to arrive at a solution. The idea... attach a click event to the button and inspect its "detail" property for the total number of clicks. If the user clicks more than twice, call clearSelection which clears the "selection" DOM element. I can also add a class to a specific block of text that sets the selected background style to transparent to prevent flashing.

I posted a JSFiddle here.

http://jsfiddle.net/vince/Ts85n/

Vince
  • 589
  • 9
  • 16