drake035
drake035

Reputation: 2897

Making a div element programmatically and vertically scroll within another div element

I want to showcase a mobile-friendly layout. To do that, I have a page with a big iPhone in it. In the screen area, I want my layout to appear and automatically scroll down vertically then scroll up to initial point.

I found a vertical carousel for that, but I'd like it to be automatic. Is there a simple way to achieve that?

Upvotes: 0

Views: 246

Answers (2)

arielnmz
arielnmz

Reputation: 9145

As simple as it can get (edited just for the record):

HTML:

<div id="Outer">
    <div id="Inner">
       …
    </div>
</div>

CSS:

#Outer {
    width: 300px;
    height: 400px;
    background: red;
    overflow-y: scroll;
}

#Inner {
    margin: 16px 16px;
    background: yellow;
}

Javascript:

step = 0;

int_1 = setInterval( function() {
    step++;
    Outer.scrollTop = step;
    if (step >= Outer.offsetHeight+16) {
        clearInterval(int_1);
        setTimeout( function() {
            int_2 = setInterval( function() {
                step--;
                Outer.scrollTop = step;
                if (step <= 0) {
                    clearInterval(int_2);
                }
            }, 5);
        }, 500);
    }
}, 5);

JSFiddle here.

Upvotes: 1

user3489095
user3489095

Reputation:

As you didn't give the code, I made my own prototype. Tweak this code to fit your needs, if you add code I can do it for you. Here is the basic idea.

<body style="background: grey;">
    <div style="width: 400px; height: 800px; background: white; overflow-y: hidden;" id="page">
        <div style="height: 2000px; width: 385px;">
            <div style="background: red; height: 400px; width: 400px;"></div>
            <div style="background: blue; height: 400px; width: 400px;"></div>
            <div style="background: green; height: 400px; width: 400px;"></div>
            <div style="background: yellow; height: 400px; width: 400px;"></div>
            <div style="background: purple; height: 400px; width: 400px;"></div>
        </div>
    </div>
    <script>
        var page = document.getElementById('page');
        var times = 0;
        window.setInterval(function(){
            times++;
            page.scrollTop = times;
            if(times == 1200){
                window.clearInterval();
            }
        }, 5);
    </script>
</body>

If you want it to come back up after completing just add page.scrollTop = 0 at the end. If you want to run it again set times to 0 and run that interval again by putting it into a function, right after clearInterval();.

I hope I helped! If there's something you're not clear about just comment below.

Finished one: jsFiddle

Upvotes: 1

Related Questions