Tuesday, December 20, 2011

Determing What Element is Selected (Part 2)

This post looks at the same element selections used in the previous post but this time, it is the end of the element selection that is of interest. Adapting getElementSelectionStart() is straight-forward as shown here:

function getElementSelectionEnd(doc) {
    var eLoc, eRange, locInfo;
    eRange = doc.ElementSelection;
    locInfo = {
        'parent' : eRange.end.parent,
        'child' : eRange.end.child,
        'offset' : eRange.end.offset
    };
    return locInfo;
}

In the case where the root element is selected, the parent element end is null and the child is null and the offset is 0. This makes sense as selecting the root element is equivalent to selecting the whole flow. There are no elements beyond that point.


If an element other than the root element is selected and that element has no sibling following, the end child is null because its location is just beyond the last character in the selected element. The parent is the parent of the selected element.

In the case where the title element is selected there is a child element at the end of the selection as title has a "younger" sibling prolog.


This third example has an insertion point between the "o" and the "t" in "Motor" in the first document paragraph. In this case, the end parent element is p (the paragraph element), and there is no child element. The offset from the start of p is 2. This is exactly the same as was the case with the start element location as with an insertion point, as with an insertion point the starting and ending locations are the exactly same.


2 comments:

  1. Hi Debra.

    Great blog. Question though: Would you recommend using the Doc.ElementSelection object as a way to ASSIGN a selection (i.e. to actually select)? I realize this is the other way around from using it to describe the user-selected selection but it seems necessary for what I want to do.

    Thanks,

    C Chew.

    ReplyDelete
    Replies
    1. Thanks for your comment.

      You can make a selection. Basically you need to set up the desired ElementRange and then set the current selection to that range. I am working on an example. Look for it in a day or two.

      Delete