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.
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:
<span>
.$.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 div
s 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With