7

How do I get the offset of an element from the right side, relative to the window?

I can only find jQuery solutions but I need a solution using vanilla JavaScript.

This is the solution using jQuery

var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

How do I translate this to vanilla JavaScript?

Bharata
  • 13,509
  • 6
  • 36
  • 50
Red
  • 6,599
  • 9
  • 43
  • 85

6 Answers6

9

You could try using element.getBoundingClientRect() to achieve that behavior. If you wrote your code to use this instead of jQuery, it would look something like:

var rt = window.innerWidth - element.getBoundingClientRect().right;
MysterX
  • 2,318
  • 1
  • 12
  • 11
1
  • You can get the width of an element using .innerWidth
  • You can get the offset values of a element using getBoundingClientRect()
  • You can get the outerWidth using offsetWidth

Porting your solution would be something like this:

window.innerWidth - (element.getBoundingClientRect().left + element.offsetWidth)

For more info you can check this link

0

You can get the offset left position using the .offsetLeft attribute on an element. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft

For outer width see this answer: outerWidth without jquery

So it would be written something like:

var rt = function() {
  var someElement = document.getElementById('someID');
  return window.innerWidth - (someElement.offsetLeft + someElement.offsetWidth);
}
Simeon Smith
  • 106
  • 6
0

Just grab the window size and subtract the x offset plus the width of the element you want to get the offset for.

function windowOffsetRight (ele) { 
    let rect = ele.getBoundingClientRect (); 
    let width = document.documentElement.getBoundingClientRect().width;
    return  width - ( rect.x + rect.width)
}
Moritz Roessler
  • 8,542
  • 26
  • 51
0

You just need to translate the jQuery functions in vanilla JS.

$window() // jQuery
window // Vanilla JS

$whatever // jQuery (probably a variable of $('.whatever'))
document.querySelectorAll('.whatever') // Vanilla JS

offset().left // jQuery
offsetLeft // Vanilla JS

outerWidth() // jQuery
offsetWidth // Vanilla JS

const el =  document.getElementById('test');
console.log(window.innerWidth - (el.offsetLeft + el.offsetWidth));
<div id="test"></div>

Of course there are many other ways how to do it.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Reza Saadati
  • 5,018
  • 4
  • 27
  • 64
0

None of the above answers returned the correct value in my case, if there was scrolling involved. Here's what did the trick in my case:

var clientRect = document.querySelector("#element").getBoundingClientRect();
var offset = { 
    top: clientRect.top + window.scrollY, 
    left: clientRect.left + window.scrollX, 
};

console.log(offset);
Inc33
  • 1,747
  • 1
  • 20
  • 26