AR_HZ
AR_HZ

Reputation: 365

Jquery offset().left and position().left returns unexpected value

I am trying to get the left position value for the sentences in a each paragraphs. I tried .offset().left and position().left but they are both returning wrong/unexpected value. They always return 18.

Take a look at: https://jsfiddle.net/9tgkvqgk/1/

var offset = $(this).offset();
var position = $(this).position();
$('i').html(offset.left + " - - - " + position.left);//display

It looks like span with single line returns correct/good value but multiple line sentences does not.

I am trying to show a tooltip and I need to display it always in the div#frame element. I was trying to get the left value of the beginning of the sentence so I can display the tooltip in right place.

Anybody have any idea why it is not showing the right value or how do I find out whether sentence is beginning from left side, center or right.

Thanks.

Upvotes: 0

Views: 1507

Answers (1)

Blazemonger
Blazemonger

Reputation: 93003

The value returned isn't "wrong." The element is, basically, being wrapped in an invisible box, and the left offset of that box is returned. Since it spans multiple lines, that offset equals the left margin of the paragraph, which isn't what you expected. What you want is the offset of the first letter of the <span>, not the offset of the entire <span>.

Try using a variation on this answer to wrap a new child span around the first letter of the string, and get the offset of that instead.

function spanFirstLetter(elem) {
  var elem = $(elem).contents().filter(function() {
      return this.nodeType == 3
    }).first(),
    text = elem.text().trim(),
    first = text.slice(0, 1);
  if (!elem.length) return;

  elem[0].nodeValue = text.slice(first.length);
  // wrap the first letter in a unique class
  elem.before('<span class="first-letter">' + first + '</span>');
};

$('#frame p').find('span').hover(
  function(e) {
    // IN
    $(this).addClass('y');
    spanFirstLetter(this); // wrap the first letter
    var offset = $('.first-letter',this).offset(); 
  // get the first letter offset
    var position = $('.first-letter',this).position();
    $('i').text(offset.left + " - - - " + position.left);

  },
  function(e) {
    // OUT
    $(this).removeClass('y')
        .find('.first-letter').replaceWith($('.first-letter',this).text());
  // remove the first-letter span by replacing it with its own .text()
  }
)

https://jsfiddle.net/9tgkvqgk/5/

Upvotes: 1

Related Questions