JQuery highlight inner Div text, OnClick

I'm trying to auto-select text <pre>

so it's easier to copy ... Here's what I worked 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>
      

Run codeHide result


The posts I was looking for refer to "highlight" as the background, but I want to actually highlight it so the user can easily copy it. How can I change the JS above so that when the user clicks on the text, it highlights it?

+3


source to share


1 answer


Your code is pretty much. There's only one small change to be made.

text = $(this)

      

should become

text = this

      



The functions you use text

as a parameter are Vanilla JavaScript methods, so expect a DOM node, not a jQuery object. "This" itself is a DOM node in this case. But by wrapping it in $ (), it turns it into a jQuery object, which is then unusable for functions that you call later.

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>
      

Run codeHide result


+8


source







All Articles