I\'m trying to get the position of an element within the window like so:
var link = $(element);
var offset = link.offset();
var top = offset.top;
var left =
You can use the .position() for this
var link = $(element);
var position = link.position(); //cache the position
var right = $(window).width() - position.left - link.width();
var bottom = $(window).height() - position.top - link.height();
Here is a jquery function that returns an object of any class or id on the page
var elementPosition = function(idClass) {
var element = $(idClass);
var offset = element.offset();
return {
'top': offset.top,
'right': offset.left + element.outerWidth(),
'bottom': offset.top + element.outerHeight(),
'left': offset.left,
};
};
console.log(elementPosition('#my-class-or-id'));
I think
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>
<script>
(function(){
var link=$("#result");
var top = link.offset().top; // position from $(document).offset().top
var bottom = top + link.height(); // position from $(document).offset().top
var left = link.offset().left; // position from $(document).offset().left
var right = left + link.width(); // position from $(document).offset().left
var bottomFromBottom = $(document).height() - bottom;
// distance from document's bottom
var rightFromRight = $(document).width() - right;
// distance from document's right
var str="";
str+="top: "+top+"<br>";
str+="bottom: "+bottom+"<br>";
str+="left: "+left+"<br>";
str+="right: "+right+"<br>";
str+="bottomFromBottom: "+bottomFromBottom+"<br>";
str+="rightFromRight: "+rightFromRight+"<br>";
link.html(str);
})();
</script>
The result are
top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731
in chrome browser of mine.
When the document is scrollable, $(window).height()
returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .
var link = $(element); var offset = link.offset(); var top = offset.top; var left = offset.left; var bottom = top + link.outerHeight(); var right = left + link.outerWidth();
Instead of
var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;
Why aren't you doing
var bottom = $(window).height() - top - link.height();
Edit: Your mistake is that you're doing
bottom = offset.top - bottom;
instead of
bottom = bottom - offset.top; // or bottom -= offset.top;
Vanilla Javascript Answer
var c = document.getElementById("myElement").getBoundingClientRect();
var bot = c.bottom;
var rgt = c.right;
To be clear the element can be anything so long as you have allocated an id to it <img>
<div>
<p>
etc.
for example
<img
id='myElement'
src='/img/logout.png'
className='logoutImg img-button'
alt='Logout'
/>