You can use getBoundingClientRect
to attach the current position of an element to the screen.
//todas as paginas ocupam toda a tela.
var pages = [].slice.call(document.querySelectorAll('.page'), 0);
var checkCurrentPage = function () {
// obtendo posição das paginas.
var tops = pages.map(function (page) {
var position = page.getBoundingClientRect();
return position.top;
});
var indexUnique = tops.indexOf(0);
if (indexUnique != -1) {
// unica pagina sendo exibida;
console.log([pages[indexUnique]]);
return;
} else {
// obtendo as paginas que começam acima da posição atual.
var prevs = tops.filter(function (top) {
return top < 0;
});
var prev = pages[prevs.length - 1];
var next = pages[prevs.length];
console.log([ prev, next ]);
}
}
window.addEventListener("scroll", checkCurrentPage);
window.addEventListener("resize", checkCurrentPage);
html, body {
position: relative;
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
.page {
position: relative;
width: 100%;
height: 100%;
}
.page1 {
background-color: #009688
}
.page2 {
background-color: #FF9800
}
.page3 {
background-color: #673AB7
}
<div class="page page1">
</div>
<div class="page page2">
</div>
<div class="page page3">
</div>
If you need to know if a particular element is within the current viewport (even if only partially) then you should compare the return of getBoundingClientRect
with window.innerWidth
and window.innerHeight
.
var position = page.getBoundingClientRect();
var vpWidth = window.innerWidth;
var vpHeight = window.innerHeight;
var visibleY = (position.top <= 0 && position.bottom > 0) || (position.top > 0 && position.top < vpHeight);
var visibleX = (position.left <= 0 && position.right > 0) || (position.left > 0 && position.left < vpWidth);
return visibleY && visibleX;
If the element you need is completely visible inside the screen.:
var position = page.getBoundingClientRect();
var vpWidth = window.innerWidth;
var vpHeight = window.innerHeight;
var visibleY = position.top >= 0 && position.bottom <= vpHeight;
var visibleX = position.left >= 0 && position.right <= vpWidth;
return visibleY && visibleX;