On my website, when a button is clicked, I dynamically create a div that includes a grid of images. The process goes like this:
$('.prod-images').click(function(){
var prodImages = generateProdImagesGrid(this);
$('#prod-images-grid').html(prodImages).show();
});
Everything works well with this setup. However, I also have a button that should close this div when clicked.
The issue arises when the height of the div exceeds the screen size and requires vertical scrolling. Due to various CSS styles on the page, the div always opens at the same scroll position where it was last closed. For instance, if I open it for the first time, it starts from the top which is fine. But if I scroll halfway down, then close it and reopen, it shows up at that scrolled position.
I attempted the following solution:
$('#prod-images-grid').html(prodImages).scrollTop(0).show();
Unfortunately, this approach does not work properly in Chrome because the div is not completely rendered when the scrollTop() function is executed.
The only workaround I found is to introduce a delay between rendering the div and setting the scroll position like so:
$('#prod-images-grid').html(prodImages).show();
window.setTimeout(function(){
$('#prod-images-grid').scrollTop(0);
},10000); //scroll to top after 10 seconds
However, relying on such a long delay is not an ideal solution. Does anyone have suggestions on how I can ensure that the div is rendered in a way that it always appears scrolled to the top when visible?