I have the following piece of HTML:
<div><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit <strong id="s">esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</strong></p></div>
The width of the DIV is fixed at 600px using CSS. Now, I want to find the offset().left of the <strong>
element. So I did:
alert( $("#s").offset().left );
However this does not seem to produce the right value, as I can clearly see the strong element is seen half way through the 600px width, but the offset value I get is only 8px.
How do I find the offset().left value of the inline strong element?
jQuery offset() Method The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.
jQuery . offset() will get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.
If it only spans the width of the actual content, then it's an inline element. Now for block elements, setting the width and height will change the size of the element, but not the display behavior. The elements will still stack on top of each other. For inline elements, adding width and height has no effect.
Here's what's happening:
Since the inline element spans multiple lines jQuery will give you the left-most position of that element, not the offset of the beginning of the element.
To get around this, try this plugin:
jQuery.fn.inlineOffset = function() {
var el = $('<i/>').css('display','inline').insertBefore(this[0]);
var pos = el.offset();
el.remove();
return pos;
};
The plugin will create a temporary element and insert it just before the target element - it will then return the offset of that temporary element.
Example usage:
alert( jQuery('strong').inlineOffset().left );
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