Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent the double-click select text in Javascript

Say I have an ul (li) list in the page:

<ul>
 <li>xxx<li>
 <li>xxx<li>
</ul>

The element li are clickable and double-clickable, they are attached with these events, and I return false in both of them.

$('ul li').on('click',function(){
    //do what I want
    return false;
}).on('dblclick',function(){
    //do what I want
    return false;
});

But when the user double-clicks the element, the text inside the li will be selected. How can this be prevented?

Update:

Solved now,I use the following code with the css selector by NiftyDude:

$('ul li').on('click',function(){
    //do what I want
    return false;
}).....on('dragstart',function(){return false;}).on('selectstart',function(){return false;});
like image 761
hguser Avatar asked Apr 17 '12 03:04

hguser


2 Answers

You can disable text selection using css (Note that this will effectively disable all selection methods and not just double clicking)

ul li {
   -webkit-touch-callout: none;
   -webkit-user-select: none;
   -khtml-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   user-select: none;
}

http://jsfiddle.net/T3d7v/1/

like image 77
Andreas Wong Avatar answered Oct 16 '22 09:10

Andreas Wong


You can't stop the select from happening but you can clear the selection right after it's made:

<script type="text/javascript">
document.ondblclick = function(evt) {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}
</script>

To also prevent selecting whole paragraph by "triple click", here is the required code:

var _tripleClickTimer = 0;
document.ondblclick = function(evt) {
    ClearSelection();
    window.clearTimeout(_tripleClickTimer);

    //handle triple click selecting whole paragraph
    document.onclick = function() {
        ClearSelection();
    };

    _tripleClickTimer = window.setTimeout(function() {
           document.onclick = null; 
    }, 1000);
};

function ClearSelection() {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}

Source/Live test.

This should work on any browser, please report any browser where it's not working.

like image 3
grepsedawk Avatar answered Oct 16 '22 08:10

grepsedawk