You are here: Reference > JavaScript > client-side > selection and ranges > methods > collapse (Range, TextRange)

collapse method (Range, TextRange)

Browser support:
Moves the start point of a range to its end point or vice versa.
Note: The Range object and its collapse method are supported in Internet Explorer from version 9.
When the start and end points of a range are at the same position, then the range is empty.

Syntax:

object.collapse ([toStart]);
You can find the related objects in the Supported by objects section below.

Parameters:

toStart
Optional. Boolean that indicates the direction of the collapsing.
One of the following values:
false
Default. Moves the start point to the end point.
true
Moves the end point to the start point.

Return value:

This method has no return value.

Example HTML code 1:

This example illustrates the use of the collapse method:
<head>
    <script type="text/javascript">
        function MoveButton () {
            var wanderer = document.getElementById ("wanderer");
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                if (selection.rangeCount > 0) {
                    var range = selection.getRangeAt (0);
                    range.collapse (false);
                    range.insertNode (wanderer);
                }
            }
            else {  // Internet Explorer before version 9
                var textRange = document.selection.createRange ();
                textRange.collapse (false);
                textRange.pasteHTML (wanderer.outerHTML);
                wanderer.parentNode.removeChild (wanderer);
            }
        }
    </script>
</head>
<body>
    <div onmouseup="MoveButton ()" style="width:400px; background-color:#e0f0d0;">
        Select some text with your mouse within this field.
        When the left button is released the wanderer button is placed 
        at the ending of the selection.
        Left mouse clicks also move the wanderer button in Internet Explorer, Firefox, Google Chrome and Safari.
    </div>
    <button id="wanderer">wanderer</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content