March 26, 2012

Get bottom and right position of an element

Question by Cameron

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 = offset.left;
var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;
var right = $(window).width() - link.width();
right = offset.left - right;

However the bottom and right have - in front of them… Why is this? as the numbers are correct just they should NOT be minus.

Answer by Mordhak

Instead of

var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;

Why not doing

var bottom = $(window).height() - top - link.height();

Edit : your mistake is to do

bottom = offset.top - bottom;

instead of

bottom = bottom - offset.top; // or bottom -= offset.top

Answer by Starx

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 = windows.height() - position.right - link.height();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!