On click on the html body: if element '#cap' is viewable, do something. if element '#cap' is not viewable due to being scrolled past it, do something else.
I tried @Heretic Monkey's suggestion and moved the functions to the bottom of the js file but that didn't work at all.
As requested by the moderators I am stating that I tried @Heretic Monkey's suggestion and moved the functions to the bottom of the js file but that didn't work at all.
<thead id = 'cap'>
function isInViewport(el) {
rect = el.getBoundingClientRect();
return (rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight ||
document.documentElement.clientHeight) && rect.right <= (window.innerWidth ||
document.documentElement.clientWidth));
}
box = document.querySelector('#cap');
document.addEventListener('click', function() {
if (isInViewport(box)) {
alert('true');
} else {
alert('false');
}
});
Chrome console says: blank.js:3 Uncaught TypeError: Cannot read properties of null (reading 'getBoundingClientRect')
function isInViewport(el) {rect = el.getBoundingClientRect();
Can someone explain why this code does nothing except produce a console error?