You can find a lot of search engine results when you look for methods to block the highlighting of text in your HTML. Unfortunately, the top results for disabling text selection either aren’t fully supported (the CSS way) or could cause scripting errors.
In this article, I will show you the proper, cross-browser way to disable and re-enable text selection using JavaScript.
Compatibility
This code is current as of 08/2013 and has been tested in the following listed below:
IE7, IE8, IE9, Firefox, Safari, Chrome, Opera
If you are looking to disable text selection on an iOS device, check out this demo of the simple CSS property to do that (-webkit-user-select: none;
)
The wrong way of doing it
Here is the quick and dirty way that you will come across everywhere. Avoid using this!
element.onselectstart = function(){ return false }; element.onmousedown = function(){ return false }; |
Why is this wrong? This method overwrites selectstart
or mousedown
events that those elements might have already. If you have read my other scripting articles, you know I have covered that issue more than once. What you want to do is add a new event to the stack, not overwrite it.
Also, sites that teach this method always seem to leave out the code to re-enable text selection once it has been disabled. I’ll show you that with the proper method below.
The RIGHT way of doing it
function disableSelect(el){ if(el.addEventListener){ el.addEventListener("mousedown",disabler,"false"); } else { el.attachEvent("onselectstart",disabler); } } function enableSelect(el){ if(el.addEventListener){ el.removeEventListener("mousedown",disabler,"false"); } else { el.detachEvent("onselectstart",disabler); } } function disabler(e){ if(e.preventDefault){ e.preventDefault(); } return false; } |
Put the 3 functions above anywhere in your script.
To disable text selection on an element, use disableSelect(yourElement)
.
To enable text selection on an element, use enableSelect(yourElement)
.
This way will work across browsers and will not interfere with any existing events. If this tip helped you, leave a comment!
Nice one. Helped a lot. Cheers!
Glad to help!
you can use pure css:
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
That does not work for Internet Explorer. IE has its own tag attribute (unselectable=”on”).
Also, Opera does not use -o-user-select. They went with the IE method.
this doesn’t seem to work on opera.
Good call. Confirmed that with the new version of Opera. I flipped the if/else statement and all is well again.
Does this still allow us to select text in textboxes and textareas?
I have been searching for disabling drag text selection. But most of the scripts had a side effect of preventing selection of text within textboxes and text areas.
I changed the disabler function to exclude textarea, and textboxes and other input elements.
function disabler(e){
var element = (e.target || e.srcElement);
if(element.tagName) {
console.debug(‘Tagname = ‘+element.tagName);
var tagname = element.tagName.toLowerCase();
if(tagname == ‘textarea’ || tagname==’select’ || tagname==’input’)
return false;
}
if(e.preventDefault){ e.preventDefault(); }
return false;
}
it seems to work fine in firefox 9. Did not check anywhere else. Please share your thoughts on this.
Well, you want to take out that console.debug() because that’s browser-specific and should only be used for development.
Otherwise, you can customize my simple function anyway you want, but you should test it in IE7, IE8, IE9, FF, Chrome, and Safari. It will come back and bite you if you don’t.
I’m having troubles with IE8 highlighting text on a double click — I’ve put in all the css I’ve seen and it works great for every browser except IE8. I tried the tag attribute above to no success. What is up with IE8? Thanks.
Just checked and its working fine in IE8. You have something else interfering with it.
Hi, thanks for that script.
I’ve tested the CTRL+A shorcut.
With the “wrong way”, the selection with ctrl+a is not possible in IE9 but possible in Firefox.
With the nice script above, the ctrl+a is possible in IE9 and in firefox.
Olivier
This does not work on iPad. Still trying to disable Copy/Paste functions on iPad text boxes.
El Mysterioso, that is not what this article is for. This is for keeping text from being highlighted with a mouse.
What you want is the iOS specific CSS property of
-webkit-user-select: none;
Here is a demo that disables both highlighting of text and the iOS copy/paste dialog.
Hello and thank you for example. I seem to be having some issues with it that can be seen here http://jsfiddle.net/5uG63/7/
The issue that I am having is a very specific case. In Internet Explorer (I am testing with Version 9, but I think its all versions) if you view the example and drag from left to right above the box you can see that the three is highlight. So start click in right above the dark blue border on the top of the example and then click and drag your mouse over to the right side and you can see that the three becomes highlight. The issue seems to be coming from the fact that the text is being highlight from outside of its element.
Do you know of a way to fix this?
Thanks,
Dan
Easy- you need to apply the disableSelect() to the parent. I updated your example to have a large container around your sample, that will take care of your issue.
http://jsfiddle.net/5uG63/8/
Thank you for your prompt response. If you update it can you include the link? It generates a new link every time seeing I do not have an account there. I was able to find the changes you made, and thank you for them. Unfortunately that does not solve the highlighting issue. The text is still able to be highlight using the method in my first reply.
Also something that I should have included in the previous reply is that is a code snippet from a much larger project, where the elements are draggable. Seeing that is the case I can only have this apply to each element, and not a container. When this element gets moved from its initial place inside the container that you created, then these events in that container will no longer apply so they need to follow each specific element, in this case the element with id d3. The large issue seems to be: when the text is being selected from within the element, then the CSS handles this and prevents it. When it is selected from outside the element, as described in my first reply, the CSS seems to break down.
Thanks again for your help!
Dan
Sorry I forgot the link to your updated example (I added it). From what I can tell, it took care of your problem. You can no longer drag from outside your boxes to select text in any browser.
The proper way to handle what you are describing is to run the function on the highest element available, because the effect doesn’t bubble up.
I myself have used this in a commercial project with drag and drop and experienced no issues.
No worries on the link!
Maybe I am not understanding you properly, but here is a video of me testing the solution that you posted above, and the text seems to still be able to be highlight. http://www.youtube.com/watch?v=IZrAHtJTaUY (*NO LONGER AVAIL*)
Yup, I agree about running it on the highest element possible. Not only for the fact of it bubbling up, but also when the elements drug it will stay with that element rather than the previous container. I see this creating issue when dragging seeing this will disable selection, so what I am thinking that I will do is renable selection when the mouse is over the element.
Also there seems to be tons of tutorials online about drag and drop. Most of them though miss small details. Most of them are not usable cross browser, and many have there pitfalls. There are very few, that are complete, work cross browsers, and that are implemented in the most minimalistic way possible. There are quite a few that use jQuery though. Maybe something to think about for a write up using java-script and html5 if you have experience in it? I think a lot of people would benefit.
Thanks for your help,
Dan
Yes, your video is the same thing, you just couldn’t see it. You are starting your drag outside the container. I updated your demo to show a background and the upper left is not part of it. If you drag from the green, it can’t highlight.
http://jsfiddle.net/5uG63/10/
I will let you take it from there, but that’s the overall concept. Any more help and I will have to charge you my consulting fee 🙂
Thank you once again for your reply! I understand now what you were saying. In the first link I thought you were saying that you implemented it, and I was like hm…. I see the solution that you have been speaking of.
I have enjoyed reading through your articles as this is one of my first interactions with Javascript! 🙂
I enjoy thе efforts you’ve gotten put into this, thanks for the great articles.
Thank you. After days googling finally found your nice clean solution that works. Had a button sortable list that while dragging/dropping its li items the buttons will get a blue border, and the button-text will be highlighted in blue (IE only), very annoying and distracting. The “blues” are gone now, thanks again.
Hi,
Thank you very much for posting this. This really helped me and working great.
Thanks,
Srikant.
Just saw ur article while searching for tips on how to disable test selection. Yet to try your recommended html though. So after inserting the THREE functions (all at once, right?), is there any other modification necessary again? Thanks.
Hi Bolaji. There is no modification necessary, just put the code in your page
Oops! Just observed this is for Javascript… I need code for HTML; can I still use this please?
Sorry I don’t understand what you are asking. There is no HTML that goes with this. You use the JavaScript with any HTML element
What I mean is… Can insert the code inside an already existing HTML code? Hope you understand now?
Nice tutorial very helpful
It worked, do you have a suggestion to disable right click? Specially one that works when “righttocopy” chrome addon is installed.