I am working on a Javascript code for checking if element is in viewport. But now I have a code that returns only true if the element is 100% in the viewport. Is there a way for example if there are 10 pixels returns true or if a percentage... of the element is in the viewport return true?
My code for so far
<script type="text/javascript">
var elem = document.getElementById("result");
var bounding = elem.getBoundingClientRect();
if (bounding.top >= 0 && bounding.left >= 0 && bounding.right <= window.innerWidth && bounding.bottom <= window.innerHeight) {
alert('in viewport');
}
</script>
Based on @Jorg's code, here's the same with the Intersection Observer API, which is a newer way of checking for intersections. This will work on all modern browsers ~ 93.5% according to Can I Use
This is set up to make it consider anything that's 50% within the viewport as within the threshold. I made it such a large value so it's easy to see how it works.
As you'll notice with this, the callback is only called at the threshold (after the initial check). So, if you want an accurate intersection percentage, you'll probably want to increase the number of thresholds checked.
let callback = (entries, observer) => {
entries.forEach(entry => {
entry.target.style.backgroundColor = entry.isIntersecting ? 'green' : 'red';
entry.target.innerHTML = entry.intersectionRatio;
})
}
let observer = new IntersectionObserver(callback, {
threshold: [0.5] // If 50% of the element is in the screen, we count it!
// Can change the thresholds based on your needs. The default is 0 - it'll run only when the element first comes into view
});
['div1', 'div2', 'div3', 'div4'].forEach(d => {
const div = document.getElementById(d);
if (div) observer.observe(div);
})
html,
body {
padding: 0;
margin: 0;
}
body {
height: 200vh;
width: 200vw;
}
#div1 {
position: absolute;
left: calc(100vw - 60px - 10px);
top: 10px;
height: 100px;
width: 60px;
background-color: red;
color: white;
}
#div2 {
position: absolute;
left: 20px;
top: 10px;
height: 50px;
width: 60px;
background-color: blue;
color: white;
}
#div3 {
position: absolute;
left: calc(100vw - 260px + 50px);
top: max(calc(100vh - 350px + 120px), 120px);
height: 350px;
width: 260px;
background-color: green;
color: white;
text-align: left;
}
#div4 {
position: absolute;
height: 9000px;
width: 9000px;
color: black;
background-color: yellow;
}
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<!-- enable this div to see an example of a div LARGER than your viewport. -->
<!-- <div id="div4"></div> -->