Question

Is there a way to run some code every time the web page height is changed via JavaScript? (The web page height itself, not the browser height.) I would prefer not to use jQuery if at all possible. If that's not possible, would there be another way to accomplish the following?

I am animating the height change of a div located at the bottom of the page, triggered by the user clicking a button. I want the page to remain scrolled to the bottom of the page while this is occurring. I figured I could listen for a height change event and update the scroll position each time, then it would be smooth. My current approach is to wait until the animation is completed and then scroll to the bottom, but this has no animation effects and is obviously delayed until after the entire height is updated.

Current code:
JS:

var myDiv = document.querySelector("#myDiv");
var activeClass = "activeDiv";
if (myDiv.className == activeClass) {
    myDiv.className = "";
}
else {
    myDiv.className = activeClass;
    setTimeout("window.scrollTo(0,document.body.scrollHeight)", 150);
 }

CSS:

#myDiv {
    max-height: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -ms-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
.activeDiv {
    max-height: 500px !important;
}
Was it helpful?

Solution 2

I was overthinking it. I implemented the desired behavior by simply updating the scroll position very frequently while the animation was occurring, then stopped updating once it completes. It's not the cleanest code nor is the animation buttery smooth (notably smoother on Safari than Chrome), but it's much better than no animation.

I simply replaced the code in the else statement with this:

legal.className = activeClass;
var timer = setInterval(function() { window.scrollTo(0,document.body.scrollHeight) }, 5);
setTimeout(function() { clearInterval(timer) }, 500);

OTHER TIPS

You may want to check out this previous post: Detect Document Height Change

I see 2 solutions in there for you. The accepted answer shows you how to check the document height. This can be called every time that you have make an ajax call that would cause the document height to change. The other option on that post is to use setInterval(). And basically you could use the same/similar function and just have it checked every x seconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top