Select All Div Text On Mouse Click using JavaScript

Hi! Let's see how to select all div text on single mouse click using javascript. At times you may let site users to copy block of text or code snippets. In such case users has to click on and drag the mouse to select the entire text. But you can make users to copy complete text with just a single mouse click. Say for example you have a div container with some code snippet. When user clicks anywhere inside div the whole content of the element will be selected. This will drastically improve user experience. And you can achieve it with good old javascript. Here's how to do it.

select all div text on click javascript

Selecting All Div Text on Mouse Click in JavaScript

The method I'm going to show you will not only select text inside div but works with any html element. It can be a paragraph element, textbox or text area.

Read Also

Here's the javascript function to select complete text of a given container.

Create JavaScript Function

<script type="text/javascript">
function selectAllText(id)
{
    if (document.selection)
    {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(id));
        range.select();
    }
    else if (window.getSelection)
    {
        var range = document.createRange();
        range.selectNode(document.getElementById(id));
        window.getSelection().addRange(range);
    }
}
</script>

Here's how the above javascript function works.

  • The method document.body.createTextRange() will create a text range for the entire document.
  • Next selectNode() will mark the start and end of the text inside the given container.
  • Finally select() method will select the text between the given text range

Function Usage

Create a <div> element and call the function selectAllText() on click event.

<div id="mydiv" onclick="selectAllText(this.id)">Lorem ipsum dolem</div>

Clicking anywhere inside the div will select it's entire text content. This will be very useful to copy paste code snippets or other texts with just a single mouse click.

As I already said you can replace the div container with any other html element. The same function will work for them as well.

If you want to implement something similar with jquery you have to use select() function.

$("#mydiv").focus(function() {
    var $this = $(this);
    $this.select();
});

Likewise you can select all div text with single mouse click in javascript. I hope you find this script useful. Meet you in another interesting tutorial :)

2 comments:

  1. thank u blogger

    ReplyDelete
  2. Thanks for sharing this informative content with us. We are working on html5 video player . It is really helpful for me and I get my lots of solution.

    ReplyDelete