0

I have content that hard-breaks and autowraps within a div container. When the user clicks on a word (or image) I want to detect which "line number" was clicked on. I've looked into DOM Level 2 objects like Range and Selection, but there doesn't seem to be any non-convoluted way that I can think of to get this done. How can I do this?

--Edit--

    $('span').click(function() {
    alert($(this).index())
})

Here's my attempt using jquery's index() method: http://plnkr.co/edit/dayeGALdxTAC0HadjGIi?p=preview

The problem is that it gives me the line of the source code; I'm interested in knowing which line it's actually rendered on.

1 Answers1

0

One possible way could be using top offset of span. If top offset of a span is larger than that of it's immediate predecessor, then a line break has occurred.

var line = 0; var prev = 0;

$("span").each(function(e, i) {

  var currentSpan = $(i);
  if (currentSpan.offset().top > prev) {
    line++;

  }
  currentSpan.attr('data-line-number', line);
  prev = currentSpan.offset().top;
})


$("span").click(function() {
  alert($(this).attr('data-line-number'))
})

Note :

  • It assumes that each word enclosed in span tag.
  • Might behave wrongly with empty new lines.

var line = 0;
var prev = 0;
$("span").each(function(e, i) {

  var currentSpan = $(i);
  if (currentSpan.offset().top > prev) {
    line++;

  }
  currentSpan.attr('data-line-number', line);
  prev = currentSpan.offset().top;
})


$("span").click(function() {
  alert($(this).attr('data-line-number'))
})
#content {
  width: 200px;
  border: solid 2px black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="content">
  <span>AAA</span><span>AAA</span><span>AAA</span><span>AAA</span><span>AAA</span>
  <span>BBB</span><span>BBB</span><span>BBB</span><span>CC</span>
  <span>AAA</span><span>AAA</span><span>AAA</span><span>AAA</span>
  <span>AAA</span>
  <span>BBB</span><span>BBB</span><span>BBB</span><span>CC</span>
</div>
Ankit
  • 1,471
  • 17
  • 29