12

In my web app the user can sometimes click the same button a number of times, skipping through messages and things, causing the </a> to be selected.

So how can I prevent this using Javascript (jQuery)

Blowsie
  • 40,239
  • 15
  • 88
  • 108
Ben Shelock
  • 20,154
  • 26
  • 92
  • 125
  • Will it prevent them from continuing to cruise messages? If not, then I would recommend against it as it will probably also prevent when they WANT to select text. – Gordon Gustafson Aug 12 '10 at 16:35
  • Doesn't sound to me like it'll affect their ability to navigate--just accidentally select. The link that Marek's included in his answer below allows disabling text selection only on certain elements. Presumably Ben will only disable selection on the one tag that's killing his users. – sblom Aug 12 '10 at 16:47

2 Answers2

29

You dont need script for this, here is the css:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
Blowsie
  • 40,239
  • 15
  • 88
  • 108
  • 2
    The person asking probably pre-decided that they want to use JS for this, but your answer is far better than any script. +1 – mavrosxristoforos Feb 12 '13 at 16:43
  • 1
    Works in Chrome 25, but does not work for me in IE10. Ctrl+A selects all text on the page. It stops text from being selected if I double click on the text, but if I drag from an area that is not using this CSS into the area that is using this CSS, it still highlights the text. – Garry English Jul 04 '13 at 20:41
2

This solution worked for me: http://chris-barr.com/entry/disable_text_selection_with_jquery/

$(function(){
    $.extend($.fn.disableTextSelect = function() {
        return this.each(function(){
            if($.browser.mozilla){//Firefox
                $(this).css('MozUserSelect','none');
            }else if($.browser.msie){//IE
                $(this).bind('selectstart',function(){return false;});
            }else{//Opera, etc.
                $(this).mousedown(function(){return false;});
            }
        });
    });
    $('.noSelect').disableTextSelect();//No text selection on elements with a class of 'noSelect'
});
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
Marek Kowalski
  • 1,782
  • 9
  • 11
  • That url seems to have moved to: http://chris-barr.com/index.php/entry/disable_text_selection_with_jquery/ – EricP Nov 17 '11 at 04:50
  • The example in the link does not work with the latest version of Jquery. $.browser no longer exists. – Garry English Jul 04 '13 at 20:44
  • 2
    For those who came across this answer, the CSS method described by Blowsie is a much better solution (and does the same thing as the linked jQuery answer). – Lachlan McDonald Aug 02 '15 at 08:04