What I’m trying to achieve is an event to trigger on a div when the div scrollheight reaches the bottom;
The code I have kind of resembles what I’m trying to achieve however this does not work.
<div id="testNav"></div>
<script>
window.onscroll = function()
{
var objDiv = document.getElementById("testNav");
var DivHeight = objDiv.scrollHeight;
var clientHeight = document.getElementById('testNav').clientHeight;
if(DivHeight >= clientHeight)
{
alert("bottom");
}
}
</script>
thanks for any help
>Solution :
The issue with your code might be that you are attaching the on scroll event to the window object instead of the TestNav div. Here’s an updated code that should work as expected:
<div id="testNav" style="height: 100px; overflow-y: scroll;">
<!-- Add your content here -->
</div>
<script>
var testNav = document.getElementById('testNav');
testNav.addEventListener('scroll', function() {
if (testNav.scrollTop + testNav.clientHeight >= testNav.scrollHeight) {
alert('bottom');
}
});
</script>
In this code, we are adding a scroll event listener to the testNav div. When the user scrolls the div, the function inside the event listener will be executed. This function checks if the sum of the scrollTop and clientHeight properties of the div is equal to or greater than the scrollHeight. If it is, then we can assume that the user has scrolled to the bottom of the div and we can trigger our desired action. Note that we also added some CSS to the div to give it a fixed height and a scrollable overflow.