Skip to content Skip to sidebar Skip to footer

Getting A Specific Line Using JQuery

Is there a way to get, let say, the 5th line ( the offset of its first letter ) of a block's content using jQuery ? I mean the visual line, the browser computed line, and not the l

Solution 1:

jQuery.fn.line:

jQuery.fn.line = function(line) {

    var dummy = this.clone().css({
            top: -9999,
            left: -9999,
            position: 'absolute',
            width: this.width()
        }).appendTo(this.parent()),
        text = dummy.text().match(/\S+\s+/g);

    var words = text.length,
        lastTopOffset = 0,
        lineNumber = 0,
        ret = '',
        found = false;

    for (var i = 0; i < words; ++i) {

        dummy.html(
            text.slice(0,i).join('') +
            text[i].replace(/(\S)/, '$1<span/>') +
            text.slice(i+1).join('')
        );

        var topOffset = jQuery('span', dummy).offset().top;

        if (topOffset !== lastTopOffset) {
            lineNumber += 1;
        }

        lastTopOffset = topOffset;

        if (lineNumber === line) {

            found = true;
            ret += text[i];

        } else {

            if (found) {
                break;
            }

        }

    }

    dummy.remove();
    return ret;

};

Usage:

$('#someParagraph').line(3); // blah blah blah

Example: http://jsbin.com/akave

How it works:

It goes through the entire element (actually, a clone of the element) inserting a <span/> element within each word. The span's top-offset is cached - when this offset changes we can assume we're on a new line.


Solution 2:

Well, there's a way to guesstimate it, and it's not pretty, but I've used it before.

The algorithm basically goes like this:

  1. Create a "test" node, absolutely positioned within the block you want to measure.
  2. Put some text in that test node.
  3. Get the height of that test node. (We'll call it H.) This is your estimated height for a line.
  4. Now create a duplicate block, with no text in it.
  5. Iterate through a loop that will -- a) Take the content from the block, and add one word at a time to the new duplicate block. b) Check the height of the block. If the height falls between 4H and 6H, then you are within the range of the 5th line. Append that text to a buffer variable.
  6. Your buffer variable will contain the text that is displayed on the fifth line.

It's not pretty but it works if you duplicate the elements right.


Solution 3:

you could use javascript's .split() and deliminate by "<br>".

split tutorial


Post a Comment for "Getting A Specific Line Using JQuery"