6

I'm using CSS3's support for columns support in a project (so far I've found it much more robust and dependable than most JavaScript solutions out there).

Question: Is it possible to get the text that is in a specific column, in any way?

mattsven
  • 22,305
  • 11
  • 68
  • 104

2 Answers2

7

And...what, two months later? I finally found the answer to this question. It's reliant on document.caretRangeFromPoint (Webkit) or document.caretPositionFromPoint.

var getAllTextInColumn = function(rect){
    /*
        rect should be the size and x,y of the column
        { top, left, width, height }
    */

    if(document.caretRangeFromPoint){
        var caretRangeStart = document.caretRangeFromPoint(rect.left, rect.top);
        var caretRangeEnd = document.caretRangeFromPoint(rect.left+rect.width-1, rect.top+rect.height-1);
    } else {
        return null;
    }

    if(caretRangeStart == null || caretRangeEnd == null) return null;

    var range = document.createRange();
    range.setStart(caretRangeStart.startContainer, caretRangeStart.startOffset);
    range.setEnd(caretRangeEnd.endContainer, caretRangeEnd.endOffset);

    return range.toString();
};
mattsven
  • 22,305
  • 11
  • 68
  • 104
  • And that column has to be on-screen, I think range is relative to viewport – mattsven Sep 29 '13 at 10:05
  • 1
    You can make an iframe off the screen and use this code and then the column doesn't have to be on-screen – Michael Bates Apr 03 '14 at 08:08
  • @MichaelBates I'm not saying it doesn't (I'm sure it does), just not sure how many use-cases that would fit into. – mattsven Apr 04 '14 at 02:11
  • @mattsven this is really nice, but how do i get `rect` of a column? – mehdok Apr 04 '15 at 16:22
  • You're going to have to calculate that from whatever element is being split into columns. Try [`element.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) for starters. – mattsven Apr 04 '15 at 18:39
  • Works perfectly except when you have multiple elements that have been split across columns. A table, flex boxes, floats with text between them, etc. – Silviu-Marian May 25 '17 at 15:27
1

My only guess is to start replacing spaces with a SPAN, then detecting when the vertical position of that SPAN gets smaller, then you know you're in the next column. This last SPAN becomes a column marker.

You can then copy the text that is between the beginning/end and/or a column maker.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176