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;
padding: 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>