Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent link dragging, but still allow text highlighting

I have some data in a table where clicking it will navigate you elsewhere, but people are requesting the ability to highlight the text to be able to copy/paste it elsewhere. Since they are links, the default behavior in HTML is to drag the link... I don't know why or how that is useful, but I want to disable that on certain links.

TL;DR: I want to be able to highlight the text of a link and not drag it.

The gif below should help explain my issue.

Example

The following methods are NOT what I want:

I have seen examples that prevent both highlighting & dragging using something like this

<a draggable="false" href="#">

or this

.no-drag {
  user-drag: none;
}

Or this

myElement.ondragstart = function () {
    return false;
};

But obviously that is not what I need here.Is what I want possible to do?

like image 663
FiniteLooper Avatar asked Oct 23 '15 19:10

FiniteLooper


1 Answers

@Julien Grégoire's answer above put me on the right track for this, but the below code is the basics of what I ended up using.

var clickedEl = document.getElementById("test");
var limit = 5;
var mouseMoved = false;

function resetEvents() {
    clickedEl.onmousemove = null;
    clickedEl.ondragstart = null;
    clickedEl.onmouseleave = null;
    mouseMoved = false;
}

clickedEl.onmousedown = function (downEvent) {
    if (clickedEl.attributes.href) {
        clickedEl.onclick = function (clickEvent) {
            if (mouseMoved) {
                clickEvent.preventDefault();
            }
            resetEvents();
        };
    }
    
    clickedEl.onmouseleave = function () {
        resetEvents();
    };

    clickedEl.onmousemove = function (moveEvent) {
        // This prevents the text selection being dragged
        clickedEl.ondragstart = function (dragEvent) {
            dragEvent.preventDefault();
        };

        if (Math.abs(moveEvent.x - downEvent.x) >= limit || Math.abs(moveEvent.y - downEvent.y) >= limit) {
            // If user clicks then moves the mouse within a certain limit, select the text inside
            window.getSelection().selectAllChildren(clickedEl);
            mouseMoved = true;
        }
    };

};
<a id="test" href="http://stackoverflow.com">Click or select</a>
like image 119
FiniteLooper Avatar answered Oct 05 '22 17:10

FiniteLooper