Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get offset right in vanilla JavaScript

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?

like image 959
Red Avatar asked Mar 05 '23 21:03

Red


2 Answers

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;
like image 86
MysterX Avatar answered Mar 11 '23 21:03

MysterX


  • 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

like image 38
Luis felipe De jesus Munoz Avatar answered Mar 11 '23 22:03

Luis felipe De jesus Munoz