tags:

views:

2875

answers:

4

Here is an interesting CSS questions for you!

I have a textarea with a transparent background overlaying some TEXT that I'd like to use as a sort of watermark. The text is large and takes up a majority of the textarea. It looks nice, the problem is when the user clicks in the textarea it sometimes selects the watermark text instead. I want the watermark text to never be selectable. I was expecting if something was lower in the z-index it would not be selectable but browsers don't seem to care about z-index layers when selecting items. Is there a trick or way to make it so this DIV is never selectable?

+1  A: 

you can try this:

<div onselectstart="return false">your text</div>
Fortega
+3  A: 

Wouldn't a simple background image for the textarea suffice?

Joey
transparent 1x1 png should work, yeah
Jonathan Fingland
Well, I rather meant the watermark, but a transparent background image might work as well. Also you shouldn't tile very small images as some browsers get abysmally slow in that case :)
Joey
Especially since a 1000x1000 transparent png (or gif) is only 4kb.
rpflo
More like 1 KiB, actually :-)
Joey
+3  A: 

I wrote a jQuery extension to disable selection some time back. It comes in very handy for things like disabling menu item text to be selected. Follow the post on Disabling Selection in jQuery. Usage is pretty simple:

$('.button').disableSelection();

In mozilla browsers you can disable selection using CSS:

.button { -moz-user-select: none }
aleemb
+5  A: 

As Johannes has already suggested, a background-image is probally the best way to achieve this in CSS alone.

A JavaScript solution would also have to affect "dragstart" to be effective across all popular browsers.

JavaScript:

<div onselectstart="return false;" ondragstart="return false;>your text</div>

jQuery:

var _preventDefault = function(evt) { evt.preventDefault(); };
$("div").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);

Rich

kim3er