tags:

views:

184

answers:

2

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.

+1  A: 

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
+1  A: 

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

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

CodeJoust
That's a really nice, concise solution!
Acorn
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