Fabian Lurz
Fabian Lurz

Reputation: 2039

scrollTop when offset changes

I want to scroll to a specific target in my application - something like this:

 var editor = self.$el.find(".editorWrapper[data-containerid=" + containerId + "]").closest('.containerWrapper');
 $('html, body').animate({
  scrollTop: editor.position().top-5
 }, 1000);

The problem is, that there are elements which render while scrolling down -> e.g. an image or iframe gets rendered while it scrolls down.I don't know the height of that new rendered element (would be tough to get the height - but not impossible so) the scroll stops at a wrong position. Is there an easy way to scroll smoothly to an element while the offset/height changes other then saving the height of each "new rendered" element?

Upvotes: 0

Views: 1393

Answers (3)

Jamie Barker
Jamie Barker

Reputation: 8246

I would just scroll down until it actually finds the specific point. Example:

function ScrollTo(el) {
    if ($('html').scrollTop() < (el.position().top - 5)) {
        $('html').animate({
            scrollTop: $('html').scrollTop() + 1
        }, 1, 'swing', function() {
            ScrollTo(el);            
        });
    }
}
ScrollTo($('#scrollTo'));
div {
    width:400px;
}
#large {
    height:400px;
    background:red;
}
#scrollTo {
    height:400px;
    background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="large"></div>
<div id="scrollTo"></div>

You could play around with the settings to make it scroll at a decent speed for you, etc.

Upvotes: 1

Raul Fernandez
Raul Fernandez

Reputation: 118

The scroll position is probably going to change everytime an image/iframe gets rendered, so the best way is binding load events to such elements (image/iframe) that updates the scrollTop position.

Upvotes: 0

Tit-oOo
Tit-oOo

Reputation: 208

You want your page to be fully loaded you can call you script in :

$(document).load(function () {
   var editor = self.$el.find(".editorWrapper[data-containerid=" + containerId + "]").closest('.containerWrapper');
   $('html, body').animate({
  scrollTop: editor.position().top-5
 }, 1000);
});

https://api.jquery.com/load-event/

Upvotes: 0

Related Questions