Thursday, 24 July 2008

Don't select that!

Sometimes you don't want a user to be able to select a part of your website, look at the below? You may not be able to select the h1 element:

Don't Select!



This is achieved by the following:

<style type="text/css">
h1{
-moz-user-select:none;
-moz-user-focus:ignore;
cursor:pointer;  /* There's no point in having a
text cursor if you can't select the text */

}
h1::selection{
background:inherit;
color:inherit;
}
</style>

The above works in two ways. First off, if the users browser uses a gecko layout engine, then -moz-user-select:none prevents the user from selection text, and -moz-user-focus prevents the dragging of the text in firefox 3.

In other browsers (*i think* KHTML and/or webkit) if the users browser supports the CSS 3 psuedo selector ::selection, e.g. Apple Safari browser, then the colour of the text which is selected is the same as the colour when it is not selected(this is due to the color property being set to inherit). This is the same for the background property.

Just a note, notice it is ::selection, not :selection. This is because ::selection is a CSS 3 psuedo elements, and it has been decided within the CSS 3 specification that psuedo elements are identified by two colons (::).

Furthermore it is now a good time to point out that if a psuedo element is used which a browser does not recognise, e.g. ::-moz-selection (gecko equivalent to the ::selection) in a non-gecko browser, then the whole block is ignored, for instance:


h1::-moz-selection, h1::selection {}

this will result in the whole block being ignored by all browsers [that support the selection psuedo], due to the fact that they will only support one or the other, and W3C specs say that this is the case.

Finally, getting the no select to work in IE. Internet explorer doesn't support any of the above selection-preventing CSS, so instead we have to use IE specific events:
ondragstart
 and
onselectstart
.

To these events, we add "
return false
", so we have:

<h1 ondragstart="return false" onselectstart="return false">
Don't Select!</h1>

No comments: