Search code examples
javascriptcssecmascript-6anchortextselection

Auto-Selecting the Displayed Text of a Hyperlink


How can I auto-select the displayed text of a hyperlink upon hover?

let aryAnchors = [... document.getElementsByTagName("a")];
for(a of aryAnchors)
{
    a.addEventListener("mouseover",function()
    {
        // What goes here?
    });
}

or, if this can be done in CSS3, that would be even better.

Some background (if you wish):

I have a page where users often want to copy the displayed text of hyper-links into their clipboard by highlight it and hitting control-C (but there are other shortcut keys they have set up that do other things to selected text beyond just copying it to their clipboard).

Manually highlighting around a hyperlink (without clicking it, or without copying white-space on either end of your selection) is cumbersome.

Without using browser extensions, I want the displayed text of a hyperlink to become selected on hover, so that all the user has to do is hover over the hyperlink and then hit ctrl-C (as an example).


Solution

  • Not by CSS. You need JavaScript here.

    Use the selectNodeContents of the range interface to set the contents of a node to the range. Then add it to the selection object.

    Here is a crude demo snippet:

    function select(elem) {
      var range, selection;    
      selection = window.getSelection(); 
      range = document.createRange();
      range.selectNodeContents(elem);
      selection.removeAllRanges();
      selection.addRange(range);
    }
    function deselect() {
      var selection = window.getSelection(); 
      selection.removeAllRanges();
    }
    
    document.addEventListener('mouseover', textselection);
    document.addEventListener('mouseout', textdeselection);
    
    function textselection(e) {
      if (e.target.tagName === 'A') { select(e.target); }
    }
    function textdeselection(e) {
      if (e.target.tagName === 'A') { deselect(); }
    }
    * { box-sizing: border-box; padding:0; margin: 0; font-family: sans-serif;  }
    a { margin: 8px; }
    p, ul, hr { margin: 8px; }
    <p>Below is a list of links which you can select by hovering over. You need to first focus the page by clicking anywhere on the document.</p>
    <div>
      <a href="#">Link one</a>
      <a href="#">Link two</a>
      <a href="#">Link three</a>
    </div>
    <hr>
    <p>Below is a list which you cannot select by hovering over.</p>
    <ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>

    And a fiddle: https://jsfiddle.net/abhitalks/826qh1fn/