JavaScript Selections (job with vydelenijami)

In Netscape Navigator 4.0x and Internet Explorer 4.0x it is possible to receive contents of the area selected on page. In Internet Explorer 4.0x you can allocate any element, including, the text and images. As against him  in Navigator 4.0x supports only allocation of the text.


In this clause{article} we shall consider distinctions between vydelenijami in Navigator 4.0x and Internet Explorer 4.0x. Navigator 4.0x, as against Internet Explorer 4.0x, it is necessary on operational system of the client because, in some systems standard opportunities are not realized less.


Navigator 4.0x supports a unique method which returns the text of the current allocation as a line. Internet Explorer 4.0x works with allocation with the help of text areas.



As Navigator 4.0x and Internet Explorer 4.0x work with vydelenijami.


In Navigator 4.0x it is possible to allocate only the text. For example, when you will lead{will carry out} the cursor the mouse above the image, he is not highlighted. The browser simply allocates the text before and after the image. The height of allocation depends on the size of the text. It is no possible to define{determine} what text type it is selected.


Internet Explorer 4.0x in many respects differs from Navigator 4.0x. In Internet Explorer 4.0x it is possible to allocate practically all elements of page. For example, you can allocate the text, images and buttons. However, some elements, such as dropping out menus (SELECT) cannot be selected.


As against the majority of other programs, allocation in Navigator 4.0x remains active (highlighted) even if the window loses focus. For example, if you with the help of the mouse allocate area of the document, and then will press the button on page, Navigator 4.0x will not remove{will not take off} allocation from the text. As against Navigator 4.0x, allocation in Internet Explorer 4.0x is removed, when the selected element loses focus. For example, when you will press the button on page, the browser will remove{will take off} the current allocation.


In both browsers of the "fourth" generation, allocation will be removed{will be taken off}, if after allocation of a part of the document you click on the link. Therefore you cannot write a script which will ask the user to click on the link with which help the script displaying the current allocation will be started. We shall consider new events Navigator 4.0x and Internet Explorer 4.0x for display of the area selected with the user when he or she I let off{I release} the button of the mouse. In other words, we shall process allocation when there will be an event mouseup.



How to use events svjazanye with vydelenijami.


In spite of the fact that Navigator 4.0x cannot return vydelenij the text in fields text and textarea, he can react to them. Navigator 4.0x supports event onselect which starts JavaScript a code when the user allocates a part of the text in a field of the form. This event can be used for other elements of page.



<FORM>

<INPUT TYPE = "text" NAME = "data" SIZE = "30"

       onSelect = "... statements here... ">

</FORM>


Event onselect also is supported by browser Internet Explorer 4.0x, as event for fields text and textarea. This event not puzyr`kovoe, as many others in Internet Explorer 4.0x. Nepuzyr`kovye events it can be accepted only at object made event, therefore you cannot accept event of object select at a level of object document.


Internet Explorer 4.0x also supports event onselectstart which can associate with any element of page. This event occurs, when the cursor of the mouse begins allocation of one or several elements. Event is generated by an element with which allocation begins. As Navigator 4.0x does not support this event to use it  it is useless. With the help of a script it is possible to simulate this action in Netscape 4.0x. Moreover, in Navigator 4.0x allocation of the text is supported only, therefore it is not meaningful to define{determine}, how the element has generated event. The best way to react to allocation is an event onmouseup which works when the user releases{lets off} the button of the mouse. With the help of purpose  of a script on this event it is possible to check up, whether allocation has been made, and to react in appropriate way.


Event onmouseup is supported by both browsers of the "fourth" generation, therefore it is most useful. In Internet Explorer 4.0x you can use advantage of event onmouseup to find last element of allocation. Property srcElement object event refers to this element. The elementary example of processing of event which automatically defines{determines} allocation, is resulted below:



function detect (e) {

  // check if a selection exists

}


if (window. Event)

   document.captureEvents (Event. MOUSEUP);

document.onmouseup = detect;



How to receive allocation in Navigator 4.0x.


Navigator 4.0x supports a method getSelection () object document. This method returns a line containing the text of the current allocation. It is usually caused so:



document.getSelection ()


The following example shows, how the method getSelection () works



FORM NAME = "myForm">

<TEXTAREA NAME = "myArea" COLS = "40" ROWS = "4"> </TEXTAREA>

</FORM>


<SCRIPT LANGUAGE = "JavaScript">

<!--


function display () {

  if (! document.getSelection)

    return;

  var str = document.getSelection ();

  document.myForm.myArea.value = str;

}


if (window. Event)

  document.captureEvents (Event. MOUSEUP);

document.onmouseup = display;


//->

</SCRIPT>


The script displays the current allocation in a field of input. In the beginning, he specifies to a browser to grasp all events onmouseup. This way works only in Navigator 4.0x, therefore, before a call of expression, simple definition of object makes sure available browser Navigator 4.0x.


Function working on event all over again appropriates{gives} the selected text of a variable under the name str. And when to property value an element of the form the variable is appropriated{given}, allocation is displayed in a field of input. Now allocate with the mouse some text. And if you use Navigator 4.0x, allocation will immediately be displayed in a field of input.


Expression:



if (! document.getSelection)

  return;


Interrupts performance of function, if at the user the browser is started, which does not support a method getSelection () object document.


Pay attention as the format of the document has affected value returned by a method getSelection (). For example, this page uses a pair <BLOCKQUOTE...> </BLOCKQUOTE> for a space of contents that facilitates reading. If you choose some lines of the text, the second (or a third, the fourth, the fifth, etc.) the text of a line recedes, because of use <BLOCKQUOTE>. In this case, the new line will consist of return of the carriage (\r), translation of a line (\n), and five blanks. You can define{determine} what symbols transfer a line having displayed value of a line to the help of function escape ().



alert (escape (str));


Function escape () receives a line as argument and returns the same line with the replaced not text symbols on their equivalent in hexadecimal system of calculation.


With the help of regular expressions you can easily get off unnecessary symbols. In our example, a combination \r\n platformo-dependent, therefore we shall simply remove five blanks which follow after it{her}. An alternative script:



<SCRIPT LANGUAGE = "JavaScript">

<!--


function display () {

  if (! document.getSelection)

    return;

  var str = document.getSelection ();

  if (window. RegExp) {

    var regstr = unescape ("%20%20%20%20%20");

    var regexp = new RegExp (regstr, "g");

    str = str.replace (regexp, " ");

}

  document.myForm.myArea.value = str;

}


if (window. Event)

  document.captureEvents (Event. MOUSEUP);

document.onmouseup = display;


//->

</SCRIPT>


First we have defined{determined} what series of symbols has called a problem, displaying value returned by function escape (), as shown above. We have immediately paid attention to sequence from five not text symbols: %20%20%20%20%20


Therefore, function unescape () transforms these symbols and appropriates{gives} this value of a variable. Regular expression is determined as object RegExp. Pay attention to argument "g". He defines{determines} that the line should be compared again to regular expression repeatedly if the sample is found more than once. The resulting line is displayed after replacement of all sequences of five blanks with empty line.



How to use object selection in Internet Explorer 4.0x.


Internet Explorer 4.0x uses object document.selection which includes properties and some methods for management vydelenijami. The object selection gives the information on the text and elements with which the user has allocated with the help of the mouse. It can be very useful, if you want to make some actions, based that the user has allocated.


Property type object selection defines{determines} type of allocation. It is a line accessible only for reading which can accept one of the following values:

Value         The description

None         There is no allocation or a point of an insert.

Text         The text is selected only.

Control         Structures of management are selected.


Default value, naturally, "None" - when there is no allocation. Therefore, comparison of value document.selection.type with "None" in Internet Explorer 4.0x, is equivalent to comparison of value returned by a method document.getSelection () with " " in Navigator 4.0x


The object selection has the following methods:

Method         The description

clear ()         Clears contents of the current allocation.

empty ()         Removes the current allocation.

createRange ()         Creates object TextRange for the current allocation.


Let's consider the following expression:



document.onmouseup = document.selection.clear;


If you to insert this expression into a script the browser will delete all allocation. In other words, when the user allocates a part of the document, the browser immediately deletes it . If allocation contains not text elements they will be removed too. Accordingly, the page with new contents will be drawn again. Pay attention, that the method clear () is described as clear (not clear ()) because obrabotchiku events the link to function (instead of a call of function) should be appropriated{given}. Have in view of, that this script does not work in Navigator 4.0x as takes advantage of object selection.


The method empty () simply removes the current allocation. Wonderfully, but is useless to use this method, for creation of page, with impossibility of allocation.



document.onmouseup = document.selection.empty;


This expression specifies to a browser to remove any allocation existing on page. In other words, it removes illumination from allocation. Have in view of, that the method empty () besides all scrolls a working window in the top of page. Therefore, the resulted expression skrolliruet a working window to top of page, always, when you release{let off} the button of the mouse.


Method createRange () it is very simple. He returns object TextRange for the current allocation. An example:



var range = document.selection.createRange ();


Job with object, and his  data is already other history. We shall consider it in the following section of this clause{article}. Simply continue reading to learn{find out}, how to use new object, and how to write function equivalent to a method document.getSelection () in Navigator 4.0x.



How to create object TextRange in Internet Explorer 4.0x.


Object TextRange represents the text inside HTML an element. The most simple way to understand this object accessible only on platforms Win32 (Internet Explorer 4.0x), it to work with an example. See at following HTML a code:



<HTML>

<HEAD>

<TITLE> Sample Page </TITLE>

</HEAD>

<BODY>

<H1> This is a sample page. </H1>

<P> This is some sample text. </P>

</BODY>

</HTML>


Text HTML of the document is known as a stream. The stream is basically the whole code in which all tegi are removed{cleaned}. In other words, elements HTML do not influence a stream. For example, a stream in for the previous example:



This is a sample page. This is some sample text.


Object TextRange displays a stream for the set part of the document. With the help of this object you can manipulate a stream, for change of the text displayed on page. You can use this object for reception and updatings of the text in an element, for definition of a site of the specified text on page, and to carry out commands which influence display of the text. Object TextRange is usually created with the help of method TextRange () a desirable element that is shown in the following example.



var range = document.body.createTextRange ();


This method can be applied only to elements BODY, BUTTON, TEXTAREA or INPUT which has text type (type = "text").


Other way to create object TextRange is the next way use a method createRange () object document.selection:



var range = document.selection.createRange ();


After allocation of text area, you can use different methods, manipulations with object TextRange. We shall discuss these methods in the following section of this clause{article}.



How to use properties and methods of object TextRange.


In this section of clause{article} we shall consider properties and methods of object TextRange. They give an opportunity of change of the text and elements of page. For demonstrations we shall use an example from the previous unit. We shall remind it :



<HTML>

<HEAD>

<TITLE> Sample Page </TITLE>

</HEAD>

<BODY>

<H1> This is a sample page. </H1>

<P> This is some sample text. </P>

</BODY>

</HTML>


We shall refer to object TextRange displaying contents of the document - which will be returned by the following method.



var range = document.body.createTextRange


The reduced list of properties of object TextRange



Property         The description

htmlText         Returns HTML a fragment for the selected text area.

Property is accessible only to reading.


<H1> This is a sample page. </H1>

<P> This is some sample text. </P>

text         Sets or returns the text contained in a range (range). These are properties it is accessible both to reading, and for recording, it means, that you can change the current value, as well as to receive it .

boundingWidth         Returns width of a rectangular which limits text area.


305

boundingHeight         Returns height of a rectangular which limits text area


74

boundingLeft         Returns the left coordinate of a rectangular which limits text area.


12

boundingTop         Returns the top coordinate of a rectangular which limits text area.


17

offsetLeft         Returns the left coordinate of a rectangular which limits text area.


12


This property - not too most, as boundingLeft. For example, if you place a site of a code in the following definition:


<DIV STYLE = " position: absolute; left: 200 ">... </DIV>


That property will be equal 212.

offsetTop         Returns the top coordinate of a rectangular which limits text area.


17


This property - not too most, as boundingTop. For example, if you place a site of a code in the following definition:


<DIV STYLE = " position: absolute; top: 200 ">... </DIV>


That property will be equal 217.


Besides, object TextRange has many methods. - the list of most useful of them:



Method         The description

collapse ([start])         Moves points of an insert to the beginning (by default) or to the end of the current text area (if the argument is set as false)

expand (unit)         Expands area so that partial elements began to contain entirely. The method returns true if expansion has passed successfully, and false differently. Unit can accept one of the following line values.


"character"


Expands a symbol.


"word"


Expands a word. The word is a group of the symbols limited to a blank or a dividing symbol.


"sentence"


Expands the offer. The offer is a set of the words limited to a symbol of a punctuation, such as a point.


"textedit"


Expands to the whole object. In other words, area till its{her} original sizes.


This example of a script creates object TextRange for the current allocation, and guarantees that any, in part selected word will be entirely placed in object.


var range = document.selection.createRange ();

range.expand ("word");

duplicate ()         Returns a copy of parental text area (which method is caused)

parentElement ()         Returns a parental element for text area. The parental element is the minimal element concluding in text

Area.

inRange (otherRange)         Returns the logic value specifying that even one area (argument) contains in other (object)

isEqual (otherRange)         Returns the logic value specifying that even one area (argument) it is equal other (object)

scrollIntoView ([start])         It forces object to be scrolled to a seen part of a window, leveling on his  top or bottom part. If start contains value false the bottom part of object will be visible in the bottom part of a window.

Otherwise, by default, the object will be scrolled to the top part of a window.

setEndPoint (type, range)         Coordinates a final point (endpoint) one area with a final point (endpoint) another. Line the argument type sets, what final point (endpoint) will be moved, and what final point of parental area should replace her .

She supports any of the following values: "StartToEnd", "StartToStart", "EndToStart", or "EndToEnd". The second argument, range - area their which undertakes an initial final point (endpoint).

compareEndPoints (type, range)         Defines{determines}, whether there are at parental area (which method is caused) and at area set as argument (range) the general{common} final points (endpoint). This method returns-1 (if less), 0 (if are equal), 1 if it is more. The argument type should be one of: StartToEnd "," StartToStart ",

"EndToStart", or "EndToEnd". As you see, he describes comparison of final points (endpoint). Pay attention that " the final point " (endpoint) not necessarily specifies the term last position in text area. It can be either the first, or last, depending on what

Value has argument type.

select ()         Does{makes} allocation on the page, equivalent to text area


In the previous table the list of the most important basic methods of object TextRange is resulted. And in the following table the list of methods of moving is resulted. After allocation of text area you can move its{her} starting and final point, with the help of these methods. Notice, that they do not move the text on page. They simply move borders of a range, thus influencing on the selected text area.


Transfer of these methods:



Method         The description

move (unit [, count])         Changes a starting or final point of text area, for

For overlapping{blocking} some text. It is a method moves text

Area, not the text. The following argument can contain one

From the next lines:


"character"


Moves one or more symbols.


"word"


Moves one or more words. The word is a group of symbols,

Limited to a blank or a dividing symbol.


"sentence"


Moves one or more offers. The offer is

Set of the words limited to a symbol of a punctuation,

Such as a point.


"textedit"


Moves to the beginning and konku original text

Areas.

The second argument, count - sets quantity{amount} of elements for

Movings (positive, or negative). By default

It is 1. The method returns real number of the moved elements.

moveStart (unit [, count])         Too most, as move (), only moves only starting

Point. He changes a range of area moving its{her} starting

Point.

moveEnd (unit [, count])         Too most, as move (), only moves only final

Point. He changes a range of area moving its{her} final point.

pasteHTML (htmlText)         Inserts specified HTML the text, into the given area. The text entirely

Replaces the previous text and HTML the elements which are taking place in

Areas. The method cannot be used, while the document

It is loaded. Besides pay attention to, that

The inserted text and HTML elements were suitable for set

Areas. For example, attempt to insert a cell of the table in text

The area, not containing table, can force a method to insert

Element TABLE.


Remember, that text areas are not supported in Makintoshovskikh versions Inernet Explorer 4.0x. These methods and properties are actual only in Win32 versions Internet Explorer 4.0x. On this page bases of text areas, as clause{article} about vydelenijakh, instead of about text areas are considered only. In the following section of this clause{article} we shall consider mezh-brauzernuju jobs with vydelenijami.



How to receive the current allocation in Navigator 4.0x and Internet Explorer 4.0x.


Now you know how to work with vydelenijami in Navigator 4.0x (with the help of method GetSelection ()) and Internet Exporer (with the help of object TextRange), now it is high time to talk about her  mezh-brouzernom execution{performance}. Generally speaking, Navigator 4.0x supports a method document.getSelection () while Internet Explorer 4.0x supports object document.selection. On this the elementary way of definition of object looks so:



if (document.getSelection) {

  // the Navigator 4.0x code

} else if (document.selection) {

  // the Internet Explorer 4.0x code

} else {

  // the alternative code

}


At attempt will receive the current allocation (this only thing, that you can make in Navigator 4.0x) you should create object TextRange (Internet Explorer 4.0x). But not all versions Inernet Explorer 4.0x support object TextRange. For example, Mac version Internet Explorer 4.0x does not support text areas, though he and supports object document.selection (). On this we shall use logic operator AND, for check of, whether the method document.selection.createRange () is supported. Operator AND is necessary, because guarantees, that the browser will not check document.selection.createRange if its{her} parental object (document.selection) is not supported. On this, the script which returns the current allocation should have the following structure:



if (document.getSelection) {

  // the Navigator 4.0x code

} else if (document.selection ** document.selection.createRange) {

  // the Internet Explorer 4.0x code

} else {

  // the alternative code

}


The following example otobrozhaet the current allocation in a field of input:



<FORM NAME = "myForm">

<TEXTAREA NAME = "myArea" COLS = "40" ROWS = "4"> </TEXTAREA>

</FORM>


<SCRIPT LANGUAGE = "JavaScript">

<!--


function display () {

  if (document.getSelection) {

    var str = document.getSelection ();

} else if (document.selection ** document.selection.createRange) {

    var range = document.selection.createRange ();

    var str = range.text;

} else {

    var str = " Sorry, this is not possible with your browser. ";

}

  document.myForm.myArea.value = str;

}


if (window. Event)

  document.captureEvents (Event. MOUSEUP);

document.onmouseup = display;


//->

</SCRIPT>


We have explained the purpose of this script in the previous section. His  unique difference is that he is mezh-brauzernoj the version which works in Win32 versions Internet Explorer 4.0x, and also in all versions Navigator 4.0x. Simply choose a part of this document, and she will appear in this field of input:


If you have access to both browsers, you could notice, that in Internet Explorer 4.0x, as against Navigator 4.0x, does not influence accommodation of page. For example, he does not insert blanks when the text is leveled with the help blockquote. As this soderzhimeo this page it is formatted, we shall use regular expressions to get rid of superfluous blanks as it is explained in the beginning of clause{article}. - the finished code:



<FORM NAME = "myForm">

<TEXTAREA NAME = "myArea" COLS = "40" ROWS = "4"> </TEXTAREA>

</FORM>


<SCRIPT LANGUAGE = "JavaScript">

<!--


function display () {

  if (document.getSelection) {

    var str = document.getSelection ();

    if (window. RegExp) {

      var regstr = unescape ("%20%20%20%20%20");

      var regexp = new RegExp (regstr, "g");

      str = str.replace (regexp, " ");

}

} else if (document.selection ** document.selection.createRange) {

    var range = document.selection.createRange ();

    var str = range.text;

} else {

    var str = " Sorry, this is not possible with your browser. ";

}

  document.myForm.myArea.value = str;

}


if (window. Event)

  document.captureEvents (Event. MOUSEUP);

document.onmouseup = display;


//->

</SCRIPT>


Other thing to which it is necessary to pay attention, it that Internet Explorer does not insert carry of a line and return of the carriage to that place of page where the text is transferred to a new line.