abidibo.net

Scroll to top and bottom with mootools

javascript mootools webmaster

Months has passed since my last post (work, travels, marriage...) so now an easy one before detoxing myself from internet and programming and enjoying my journey to South Africa.

Let's see a way to implement the scroll to top and scroll to bottom buttons with mootools.

A bit of style

The two buttons are positioned at a fixed distance from top and bottom of the viewport. I've used font-awesome icons in my example as you will see in the js code.

.scroll {
    position: fixed;
    color: #e7e7e7;
    cursor: pointer;
}
.scroll-to-top {
    bottom: 70px;
    right: 20px;
}
.scroll-to-bottom {
    top: 80px;
    right: 20px;
}

Javascript

Actually the Fx.Scroll class of the mootools-more package is required, it's not mandatory, you may animate the motion through css3 and do some more calculating, but now I'm not dealing with performance.

window.addEvent('load', function() {
    var checkScroll = function() {
        var body_scroll = document.body.getScroll();
        to_top.setStyle('visibility', body_scroll.y > 0 ? 'visible': 'hidden');
        to_bottom.setStyle('visibility', (body_scroll.y + window.getCoordinates().height) < window.getScrollSize().y ? 'visible': 'hidden');
    }
    var scroll_fx = new Fx.Scroll(window);
    var to_top = new Element('span.scroll.scroll-to-top.fa.fa-3x.fa-arrow-circle-up')
        .addEvent('click', function() {
            scroll_fx.toTop();
        })
        .inject(document.body);
    var to_bottom = new Element('span.scroll.scroll-to-bottom.fa.fa-3x.fa-arrow-circle-down')
        .addEvent('click', function() {
            scroll_fx.toBottom();
        })
        .inject(document.body);

    checkScroll();
    window.addEvent('scroll', function(e) {
        checkScroll();
    })
})

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

* indicates required

abidibo.net topics

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured