Reputation: 155
I would like to make specific div's unselectable Double-clicks, etc. should be blocked.
<div id="test" class="unselectable">asd</div>
$(document).ready(function() {
$.ctrl = function(key, callback, args) {
var isCtrl = false;
$(document).keydown(function(e) {
if (!args) args = []; // IE barks when args is null
if (e.ctrlKey) isCtrl = true;
if (e.keyCode == key.charCodeAt(65) && isCtrl) {
callback.apply(this, args);
return false;
}
}).keyup(function(e) {
if (e.ctrlKey) isCtrl = false;
});
};
//Other Method
$(function() {
$(document).keydown(function(objEvent) {
if (objEvent.ctrlKey) {
if (objEvent.keyCode == 65) {
objEvent.disableTextSelect();
return false;
}
}
});
});
});
But I find, to my chagrin, that this fails to work. How might I modify my code to achieve my objective?
Upvotes: 0
Views: 6705
Reputation: 324507
I've answered at least three similar questions on SO with a fairly definitive answer. Here's the most popular.
I've also updated your jsFiddle with information from that answer to work in IE: http://jsfiddle.net/VYKfL/3/
Upvotes: 1
Reputation: 41209
As far as I know, there is no way to stop the user from selecting the text on a div. Since this is a browser and potentially operating-system related feature, its beyond the realm of things you can typically manipulate with Javascript.
If you wanted to be incredibly annoying to your user, you could create an event handler on the entire document that would check if the user ever pressed control-A together, and if so, try to prevent the div from being selected by preventing the default action or focusing on some other part of the page. However, this would do little more than piss them off that you are trying to keep them from using their computer the way they want to and probably make them hightail it out of your website.
Could you give us a little more background on why you don't want the user selecting something? There will always be a workaround to whatever you do, considering they can just disable javascript/CSS and reload the page. If you want to make text a little more difficult to copy-paste you can make an image containing the desired text and place that in the div instead, but you're still just spending your time just to make the user more annoyed with your website.
While I'm not going to claim in the slightest that I know your entire project so well that I can tell you exactly what you should be doing, I will say there's probably a better way to accomplish whatever goal your working towards. If you post a little more detail, we can probably help you find it. :D
Upvotes: 2
Reputation: 53291
You don't need Javascript for this (reference answer). Do this:
div {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Upvotes: 7