Nov 20, 2022

# Solution 1 :

The `x` and `y` in your example will be the first pixel outside the viewport, to the bottom right of it. Remember that these values are 0-based.

For instance, suppose `innerWidth` is 5 and `innerHeight` is 3. You’d have:

```[0, 0]  [1, 0]  [2, 0]  [3, 0]  [4, 0]  [5, 0]
[0, 1]  [1, 1]  [2, 1]  [3, 1]  [4, 1]  [5, 1]
[0, 2]  [1, 2]  [2, 2]  [3, 2]  [4, 2]  [5, 2]
```

With your current code, `[x, y]` would be `[5, 3]`, which would be here:

```[0, 0]  [1, 0]  [2, 0]  [3, 0]  [4, 0]  [5, 0]
[0, 1]  [1, 1]  [2, 1]  [3, 1]  [4, 1]  [5, 1]
[0, 2]  [1, 2]  [2, 2]  [3, 2]  [4, 2]  [5, 2]
[5, 3]
```

To get the bottom right pixel, you’d want

``````return [window.innerWidth - 1, window.innerHeight - 1];
``````

The -1 is because we’re talking about a single pixel, which is 1×1. Of course, you’d have to allow for any width and height of the element you’re adding. A 10×10 element would need -10 on both.

Example:

``````setTimeout(() => {
document.body.removeChild(document.getElementById("msg"));
const div = document.createElement("div");
div.className = "box";
document.body.appendChild(div);
div.style.left = (window.innerWidth - div.offsetWidth) + "px";
div.style.top = (window.innerHeight - div.offsetHeight) + "px";
}, 800);``````
``````/* Use border-box */
html {
box-sizing: border-box;
font-family: sans-serif;
}
*, *:before, *:after {
box-sizing: inherit;
}

/* Full viewport */
html, body {
height: 100%;
margin: 0;
}

/* Show a grey background */
body {
background-color: #eee;
}

/* Our box div */
.box {
position: absolute;
width: 10px;
height: 10px;
background-color: blue;
}``````
``<div id="msg">Box will appear in the bottom-right in 800ms...</div>``

# Problem :

I’m trying to .appendChild() an element into my viewport without introducing vertical/sideways scrolling to my browser window. If I set the x and y values as window.innerWidth and window.innerHeight, the element appears outside of my viewport. How can I fix this?

Function for width and height:

``````function XY() {
let x = window.innerWidth;
let y = window.innerHeight;
return [x, y];
}
``````

Viewport:

After appending elements:

^Notice the addition of vertical and horizontal scroll bars.