How to get right side position of element?

Viewed 1041

I have div on the page and I need to know what is its position from the right relevant to the viewport. I have tried this code:

const el = this.searchWrapper.getBoundingClientRect();
el.right 

but this is not what I need because getBoundingClientRect() starts calculation from the left side but I need calculate what is the distance between element and right side of the viewport like on the screen below enter image description here

1 Answers

You can do something like this:

const div = document.querySelector('div');
const span = document.querySelector('span');

const rect = div.getBoundingClientRect();

const position = window.innerWidth - rect.right + div.offsetWidth;

span.style.left = position + 'px';

console.log(position);
body {
  display: flex;
  justify-content: center;
}

span {
  position: absolute;
  top: 50px;
  padding: 10px;
  border-left: 1px solid
}
<div>I am a div</div>
<span>Distance from left</span>

Minus the right rect of the element from the width of the window, then add the width of the div to find the position.

If you just needed the distance from the right side of the viewport, minus position from window.innerWidth:

const div = document.querySelector('div');
const span = document.querySelector('span');

const rect = div.getBoundingClientRect();

const position = window.innerWidth - rect.right + div.offsetWidth;

span.style.right = window.innerWidth - position + 'px';

console.log(window.innerWidth - position);
body {
  display: flex;
  justify-content: center;
}

span {
  position: absolute;
  top: 50px;
  padding: 10px;
  border-right: 1px solid;
}
<div>I am a div</div>
<span>Distance from right</span>

EDIT

From right side of the window to the element's start:

const div = document.querySelector('div');
const span = document.querySelector('span');

const rect = div.getBoundingClientRect();

const position = window.innerWidth - rect.right;

span.style.right = window.innerWidth - position + 'px';

console.log(window.innerWidth - position);
body {
  display: flex;
  justify-content: center;
}

span {
  position: absolute;
  top: 50px;
  width: 120px;
  border-right: 1px solid;
}
<div>I am a div</div>
<span>Distance from the right-side of the window to the left-side of the div</span>

Related