19

How can I possibly figure out the distance from an object (div) to the right browser window border?

http://www.screencast.com/t/ryNgwa4E

Thanks!

2 Answers2

33
$(window).width() - ($('#your-element').offset().left + $('#your-element').width());

That takes the width of your element adds it to the position of the element within the document and takes it away from the whole window size which should leave you with the right hand distance between element and window.

danblundell
  • 1,443
  • 12
  • 7
  • 5
    for reference you're better off pulling your element into a var first i.e var elem = $('#your-element'); then referencing elem.offset().left; etc - saves querying the DOM everytime! – danblundell Mar 20 '12 at 18:22
  • 1
    be sure that this is not working in any case; scenario: absolute in absolute in absolute with overflow scroll => game over; – HellBaby Oct 16 '14 at 11:28
0

If you need to include element's border, replace .width() for .outerWidth():

el = $('#your-element');
$(window).width() - (el.offset().left + el.outerWidth());

Without jQuery:

elRect = document.getElementById('your-element').getBoundingClientRect();
window.innerWidth - elRect.right

For browser compatibility refer to getBoundingClientRect (IE9+)

mtbno
  • 561
  • 7
  • 12