4

What's the best way to make an element unselectable using jQuery?

I know you can use onselectstart="return false;" ondragstart="return false;" in the HTML, but I'm not sure how cross browser compatible that is.

I also see someone's made a jQuery plugin: http://plugins.jquery.com/project/Unselectable .. would a plugin like that be necessary?

Is there a simple, compatible way to make an element unselectable?

The reason for wanting to do this is purely aesthetic. With webpages that have dragging or click events, it's not very nice when things get selected.

Acorn
  • 49,061
  • 27
  • 133
  • 172
  • 1
    possible duplicate of http://stackoverflow.com/questions/924916/is-there-a-way-to-make-a-div-unselectable - Just noticed the question asks for a CSS solution but the majority of answers are JavaScript/jQuery based. Specifically, see http://stackoverflow.com/questions/924916/is-there-a-way-to-make-a-div-unselectable/924951#924951 – Andy E Apr 30 '10 at 13:04
  • Thanks, that's basically the same solution CodeJoust gave, although CJ's version is more compact :) – Acorn Apr 30 '10 at 13:11

4 Answers4

5

$('.noselect').live('selectstart dragstart', function(evt){ evt.preventDefault(); return false; });

Just bind the event to a live, and return false, or prevent default.

CodeJoust
  • 3,760
  • 21
  • 23
  • That's a really nice, concise solution! – Acorn Apr 30 '10 at 13:10
  • 1
    Thanks! Do realize that the plugin also uses CSS techniques and might be a little more bulletproof, so to say. However, if it isn't mission-critical, I prefer concision over unnecessarily complex code, usually something like this is just to improve the User Interface. – CodeJoust Apr 30 '10 at 14:31
  • 4
    live() is deprecated in new version of jQuery. Use "on()" instead – Giovanni Lovece Apr 05 '13 at 20:49
  • Keep in mind, this won't solve the issue if the `dragstart` event is fired outside the element. – A F Feb 26 '14 at 00:00
1

I think jQuery will abstract the browser variance & so it will help you make HTML elements unselectable.

Having said that, please note that the client can decide to switch off javascript, in which case you need to ensure that he still cannot do anything that will cause harm...

HTH.

Sunny
  • 6,286
  • 2
  • 25
  • 27
0

I believe this is a better answer.

$('*[data-noselect="true"]').focus(
    function () {
        $(this).blur();
    });

$('*[data-noselect="true"] *').focus(
    function () {
        $(this).blur();
    });

Then you can just add a data-noselect="true" to any element.

0

If you use JqueryUI you can set class="ui-state-default" to the div that you dont want to be selected.

<div class="ui-state-default"></div>
OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
shai
  • 1