JQuery Highlight Inner Text of Div, OnClick

3.6k views Asked by At

I'm trying to auto-highlight the text of a <pre> so that it's easier to copy... Here's what I've been working with:

jQuery( document ).ready( function() {
  $( 'pre' ).click( function() {
    $( this ).select();
    
    var doc = document
    , text = $( this )
    , range, selection;

    if( doc.body.createTextRange ) {
      range = document.body.createTextRange();
      range.moveToElementText( text );
      range.select();
    } else if( window.getSelection ) {
      selection = window.getSelection();        
      range = document.createRange();
      range.selectNodeContents( text );
      selection.removeAllRanges();
      selection.addRange( range );
    }
  } );
} );
pre {cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>This is Text</pre>

The posts I've searched all refer to "highlighting" as a background color but I want to actually highlight it so the user can copy it easily. How can I modify the JS above so that when the user clicks on the text it highlights it?

1

There are 1 answers

0
BurningLights On BEST ANSWER

Your code is pretty much spot-on. There's just one little change that needs to be made.

text = $(this)

needs to become

text = this

The functions you use text as a parameter to are Vanilla JavaScript methods, and so expect a DOM node rather than a jQuery object. "This" by itself in this case is a DOM node. But, wrapping it in $() turns it into a jQuery object, which is then unusable by the functions you call later on.

jQuery( document ).ready( function() {
  $( 'pre' ).click( function() {
    $( this ).select();
    
    var doc = document
    , text = this
    , range, selection;

    if( doc.body.createTextRange ) {
      range = document.body.createTextRange();
      range.moveToElementText( text );
      range.select();
    } else if( window.getSelection ) {
      selection = window.getSelection();        
      range = document.createRange();
      range.selectNodeContents( text );
      selection.removeAllRanges();
      selection.addRange( range );
    }
  } );
} );
pre {cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>This is Text</pre>