Samuel Sjöberg's weblog

Skip to navigation

Show and hide scrollbars on mouseenter and mouseleave

I'm experimenting with scrollbars and how to make them look better with a design I'm working on. I really don't like messing too much with the user's settings but this time the aesthetics call for it.

After trying out a couple of plugins that really didn't do anything for me I decided to switch approach. What if we simply hide the scrollbar when the user doesn't focus on the content? I'm not sure how users will react but since it can be done, here it is:

// Trick to only show the scrollbar when focused.
$(document).ready(function() {
    $(".sneaky-scrollbar").mouseleave(function() {
        var $this = $(this);
        var padding = parseInt($this.css("padding-right"));
        $this.data("scrollTop", $this.scrollTop());
        $this.css({
            "overflow": "hidden",
            "padding-right": padding + $.getScrollbarWidth(),
            "width": $this.width() - $.getScrollbarWidth()
        });
    }).mouseenter(function() {
        var $this = $(this);
        var padding = parseInt($this.css("padding-right"));
        $this.css({
            "overflow": "auto",
            "padding-right": padding - $.getScrollbarWidth(),
            "width": $this.width() + $.getScrollbarWidth()
        });

        // Reset scrollbar before setting position again,
        // otherwise it won't update its position correctly.
        $this.scrollTop(0).scrollTop($this.data("scrollTop"));
    }).mouseleave();
});

This script depends on the $.getScrollbarWidth() plugin by Brandon Aaron. You'll need to include the linked snippet too.

Just add the sneaky-scrollbar class to the element that should hide its scrollbar. I'm assuming it has a fixed height and overflow:auto to begin with.

The code is pretty straight-forward, the only detail worth mentioning is that the scrollbar will have the wrong position once it shows again if scrolled down a bit when hidden. To fix this, I'm storing the scroll position and restore it when showing the scrollbar again. Before restorting it, I'm setting it to zero to ensure that the UI will render the update.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 16th July 2011 22:13 CET. Filed under jQuery, Javascript and DOM.

0 Comments
0 Pingbacks