Select all DIV text with single mouse click in Javascript

If you want to allow copying some text to your site visitor then as default it’s quite uncomfortable. Help your site visitors select the text with a single click of a mouse button with this simple trick. Here is the quick code in core javascript for selection div container text in just one mouse click. You only have to copy paste below javascipr code and pass the div or any element id to the below function.
select-div-text-onlick

<script type="text/javascript">
        function selectText(elementId) {
            if (document.selection) {
                var txtRange = document.body.createTextRange();
                txtRange.moveToElementText(document.getElementById(elementId));
                txtRange.select();
            }
            else {
                var txtRange = document.createRange();
                txtRange.setStartBefore(document.getElementById(elementId));
                txtRange.setEndAfter(document.getElementById(elementId));
                window.getSelection().addRange(txtRange);
            }
        }
    </script>




Testing the above code..

<div id="text1" onclick="selectText('text1')" >Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
 
<p id="text2" onclick="selectText('text2')" >
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>




See live demo and download source code.

DEMO

DOWNLOAD

If you like this post please don’t forget to subscribe my public notebook for more useful stuff