27 Apr 2014

How to Automatically Select Content of a HTML element for copy to clipboard

Sometimes you want to let your users to select certain portion of your web content for copying to clipboard, And for this user has to select content manually.
But using below mentioned script anyone can select entire content of a HTML element just by single/double click.

Steps for implementation.
First assign a 'onclick' or 'ondblclick' function with function call (as shown below)to your HTML element.For example,
      <!-- Calling select funtion on double click -->
    <div ondblclick="selectElementContents(this)"> Double click to Select content of this div !! </div>
Now define a JavaScript function named as 'selectElementContents()',
     function selectElementContents(el) {
                    if (window.getSelection && document.createRange) {
                       // IE 9 and non-IE
                       var range = document.createRange();
                       range.selectNodeContents(el);
                       var sel = window.getSelection();
                       sel.removeAllRanges();
                       sel.addRange(range);
                    } else if (document.body.createTextRange) {
                       // IE < 9
                       var textRange = document.body.createTextRange();
                       textRange.moveToElementText(el);
                       textRange.select();
                    }
            }

That's it, Now your user can select entire content just by double clicking inside the element.
Test this code by double clicking above code area.
Did you find this post useful? Let Us know in the comments section below.

0 comments:

Post a Comment