Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make certain parts of my html not selectable?

How can I make certain parts of my html not selectable?

I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.

Is there a way to make it so certain elements (such as those divs) aren't selectable?

EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

like image 382
Kyle Avatar asked Nov 30 '10 01:11

Kyle


4 Answers

For IE, add the attribute unselectable="ON". (EDIT: Although it won't completely help)

For Gecko, add the CSS style -moz-user-select: none.

For WebKit, add the CSS style -webkit-user-select: none.

like image 69
SLaks Avatar answered Sep 28 '22 06:09

SLaks


If you want to just hide selection rectangle, you can use

element::selection { background: transparent }

and it's counterpart for Gecko

element::-moz-selection { background: transparent }

If you want to help your users select right text to copy to clipboard, you can move the element away. Usually browsers retain order of elements as they are defined in HTML when selecting. While it is not perfect solution, you can place the element's code in HTML either at the very beginning or very end of <body> tag. This way, if user selects something in the middle of the page, the element will be too "far away" to interfere.

like image 40
Athari Avatar answered Sep 28 '22 05:09

Athari


this article might help with a cross-browser solution: (uses jQuery) http://aleembawany.com/2009/01/20/disable-selction-on-menu-items-with-this-jquery-extension/

in theory, you can extend the jQUery core using this:

jQuery.fn.extend({ 
    disableSelection : function() { 
            return this.each(function() { 
                    this.onselectstart = function() { return false; }; 
                    this.unselectable = "on"; 
                    jQuery(this).addClass('unselectable');
            }); 
    } 
}); 

and applying it like this:

// disable selection on selected objects 
$('.myClass').disableSelection(); 

you must make sure you have this in your stylesheet:

.unselectable {
    user-select: none; 
    -o-user-select: none; 
    -moz-user-select: none; 
    -khtml-user-select: none; 
    -webkit-user-select: none; 
}

looks as if it basically does what SLaks and Sime have mentioned. i haven't tried it, but i'd be interested to know if it works

like image 26
Sebastian Patane Masuelli Avatar answered Sep 28 '22 05:09

Sebastian Patane Masuelli


You can use the ::selection pseudo-element to make the selection of a certain element "invisible":

p::selection { background-color:transparent; }  
p::-moz-selection { background-color:transparent; }

However, that doesn't work in IE.

like image 27
Šime Vidas Avatar answered Sep 28 '22 07:09

Šime Vidas