I want to get an element's position relative to the window (fixed position).
Here's what I've got so far:
(function ($) {
$.fn.fixedPosition = function () {
var offset = this.offset();
var $doc = $(document);
return {
'x': offset.left - $doc.scrollLeft(),
'y': offset.top - $doc.scrollTop()
};
};
})(jQuery);
$('#thumbnails img').click(function () {
var pos = $(this).fixedPosition();
console.log(pos);
});
But when I click a thumbnail, it appears to be off by about 10 pixels or so. i.e., it will give me negative values for y
even when the top edge of the photo is about 5 pixels away from the top of my browser window.
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.
Update:
Solution now depends on JSizes and a couple helper methods:
function Point(x, y) {
return {
'x': x,
'y': y,
'left': x,
'top': y
};
}
$.fn.outerOffset = function () {
/// <summary>Returns an element's offset relative to its outer size; i.e., the sum of its left and top margin, padding, and border.</summary>
/// <returns type="Object">Outer offset</returns>
var margin = this.margin();
var padding = this.padding();
var border = this.border();
return Point(
margin.left + padding.left + border.left,
margin.top + padding.top + border.top
);
};
$.fn.fixedPosition = function () {
/// <summary>Returns the "fixed" position of the element; i.e., the position relative to the browser window.</summary>
/// <returns type="Object">Object with 'x' and 'y' properties.</returns>
var offset = this.offset();
var $doc = $(document);
var bodyOffset = $(document.body).outerOffset();
return Point(offset.left - $doc.scrollLeft() + bodyOffset.left, offset.top - $doc.scrollTop() + bodyOffset.top);
};
Use:
element.getBoundingClientRect();
In a JQuery Plugin:
$.fn.fixedPosition = function () {
var rect = this.getBoundingClientRect();
return {
x: rect.left,
y: rect.top
};
};
See:
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