Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find absolute or relative position of text or <br /> in HTML?

I was wondering if there is a way I could find the position of letters in HTML using Javascript or jQuery? I highly doubt this is possible, but it would make my life so much easier.

Alternatively, Is there a way to find the position of <br /> tags in HTML using JS?

Thanks in advance.

like image 267
Roozbeh15 Avatar asked Feb 11 '12 09:02

Roozbeh15


1 Answers

As tdammers mentions, handling all of the details of putting together a process to handle what you're suggesting has many nuances that may have to be addressed, depending on what you're doing.

The basics of what you're trying to do is:

  1. Wrap an element around the text you want to find the position for, ie, in the case of text, probably a <span>.
  2. Get either the $.offset() or $.position() of the element or elements you added. Whichever you choose is relevant to what you're trying to do; the first is relevant to the document, the second to the containing element.

I created a simple demo of a script to "highlight" a term typed into a textbox in several paragraphs using divs with position: absolute and top/left offsets relative to the terms found in the paragraphs (located by the <span> surrounding them).

Note, this is only a demonstration (of $.offset()); it's not production-ready code. There's a link to the live fiddle demo below the code snippets.

First, I created a function to find and create a highlight <div> for each term found.

function highlightWordPositions(word) {
    var $paras = $('p'),
        $spans,
        _top = 0,
        _left = 0;

    $paras.each(function(){
        var $p = $(this),
            regex = new RegExp(word, 'g');

        $p.html($p.text().replace(regex, '<span>' + word + '</span>'));
        $spans = $p.find('span');

        $spans.each(function(){
            var $span = $(this),
                $offset = $span.offset(),
                $overlay = $('<div class="overlay"/>');

            $overlay
                .offset($offset)
                .css({
                    width: $span.innerWidth(),
                    height: $span.innerHeight()
                }).show();

            $(document.body).append($overlay);
        });
    });
}

Then, I attached a callback to the $.keyup() event:

$('#term').keyup(function(event){
    var term = this.value;

    if (term == '') {
        $('.overlay').remove();
        return false;
    } else if (term.indexOf(' ') != -1) {
        this.value = term.replace(' ', '');
        return false;
    }

    $('.overlay').remove();

    highlightWordPositions(term);
});

http://jsfiddle.net/JaN75/

like image 145
Jared Farrish Avatar answered Sep 27 '22 20:09

Jared Farrish