Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable Text Selection temporarily using JavaScript?

this is a bit of a specific question so I'll get right to the point.

I'm working on a short and simple drag and drop routine for part of a web application, and although the dragging and dropping bit works fine, the site goes all ugly-tastic during the operation because the browser still does the default operation and works on text selecting.

I've tried a few solutions mainly involving returning false from the mousedown or click events, and although they disable text selection in some browsers, they also seem to disable the mouseup event entirely, ruining the "drop" bit of the script and leaving this perma-floating icon hanging around the mouse-- not fun.

I don't really want text selection to be gone entirely, I just want to suggest that the browser... not do it while dragging, if that makes sense. Since I know the area that is affected (there are iframes involved) I can easily apply a property to the affected elements, etc. I can post code if necessary, but I'm looking for more of a general solution. Since this is an aesthetics thing only, I'm looking for a fix that works in most browsers, it's not really that crucial.

Thanks!

like image 631
Nicholas Flynt Avatar asked May 21 '09 06:05

Nicholas Flynt


People also ask

How do I turn off selection text?

You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.

How do I restrict copy and paste in JavaScript?

You can use jquery for this: $('body'). bind('copy paste',function(e) { e. preventDefault(); return false; });

How do I stop text from being selected CSS?

Use the user-select: none; CSS rule.

How can I prevent text element selection with cursor drag?

To prevent text or element selection with cursor drag with JavaScript, we can use the window. getSelection(). removeAllRanges(); method in the selectstart event handler. document.


1 Answers

In W3C browsers, you can call the preventDefault method on the event object. The IE equivalent is to set the returnValue to false.

function stopDefault(e) {
    if (e && e.preventDefault) {
        e.preventDefault();
    }
    else {
        window.event.returnValue = false;
    }
    return false;
}

EDIT: Just re-read the question and you might also want to prevent the default action in the part of your code that handles the actual dragging, and not just at the initial mousedown or click.

like image 110
Bryan Avatar answered Oct 05 '22 23:10

Bryan