Bas
Bas

Reputation: 2210

jQuery scroll back to top

According to this post i asked how to make a scroll method wich shows a element, scrolls to it and hide the element where i came from.

I improved that code, and it works.

But when I try to do this backwards, so from the second screen to the first screen again. Its not working. Its only scrolling to the top of the #content screen...

How does this come?

Here's a jsFiddle:

Upvotes: 0

Views: 228

Answers (2)

Patsy Issa
Patsy Issa

Reputation: 11293

In order to achieve the desired effect you ll need to change up your markup/css and js logic a bit, as of now you are hiding the top element so once the scroll is done the bottom element's offset top = 0.

First change is to wrap your html in a <div> we ll give that div an id of #container. Second of all we need to set the container's position to absolute so that we can slide it up and down on button click.

The css :

html,body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    overflow:hidden;
}
#page1 {
    height: 100%;
    width: 100%;
}
#content {
    height: 100%;
    width: 100%;
    overflow-y:scroll;
}
#exploreBtn {
    height: 50px;
    width: 50px;
    background-color: red;
}
#goBack {
    position: fixed;
    bottom: 5%;
    right: 5%;
    height: 50px;
    width: 50px;
    background-color: purple;
}
#container {
    position:absolute;
    width:100%;
    height:100%;
}

And finally we need to change up the js:

$(document).ready(function () {
    $('#exploreBtn').on('click', function () {
        showScrollHide('#content', '#page1');
    });

    $('#goBack').on('click', function () {
        showScrollHide('#page1', '#content');
    });
});

function showScrollHide(element, hide) {
    var _ele = $(element),
        _container = $('#container'),
        _ele_top = _ele.offset().top;
    if(_ele_top < 0)
        _ele_top = 0;
    console.log(_ele_top);
    _ele.fadeIn(500, function () {
        _container.stop().animate({
            top: - _ele_top
        }, 1000);
    });
}

We get the desired effect, needs a bit of tweaking but you get the general picture. Hope i helped. The fiddle

Upvotes: 2

patrick
patrick

Reputation: 11

put this in clck handler of the back to top button: $('html').scrollTop(0);

Upvotes: 0

Related Questions