Using ScrollMenu.js

Include jquery, scrollmenu.js and scrollmenu.css to your page.

<link href="scrollmenu.css"  rel="stylesheet" type="text/css" />
<script src="jquery.js"></script> <!-- Supports jQuery 1.7 plus-->
<script src="scrollmenu.js"></script>
    

HTML Structure required

        

Initializing plugin

        var myScrollMenu = ScrollMenu([wrapper] [,options]);
    

ScrollMenu looks for section class (which can be modified trough options ) to identify different section of page.

ScrollMenu accepts two parameter
  1. wrapper (optional): wrapper can be a selector, dom element or jquery object. If wrapper not defined scrollMenu will be initialized to body.
  2. options (optional): Different configuration options to make ScrollMenu fit your requirement and to add unique touch to it.

Understanding ScrollMenu

ScrollMenu consist of three important part each contain there classes and can be styled differently through css.

  1. Anchors (className : scroll-anchor): Anchors represents a sections of page in scrollbar. Height of an anchor in vertical scrollmenu and width in horizontal scrollmenu is proportion to height of respective sections. It gives a insight of how much big a section is and how much part is currently visible in viewport.
  2. Handles (className : scroll-handle): Handles are the scrollbar handles for scrollmenu.
  3. Menu (className : scroll-menu-content): Menu contains the label or snap of a section. This is part where you can be most creative and have a unique scrollmenu for your website. Plugin allow to template your menu and provides different callbacks so you can easily handle different states of menu. It also adds an hovered class to whenever an anchor is hovered, so that you can handle hover states through css.

Types of ScrollMenu

There are three basic types of scrollmenu, but with customizing options results can be limitless. By default its a vetical type, which can be changed using menuType options.

  1. vertical : A vertical scroll menu.
  2. vertical : A horizontal scroll menu.
  3. horizontal-menu :A fixed static horizontal menu, generally lies on headers.

Templating menu & Anchor setup

To provide customizability to have unique menu for your scroll menu, plugin provides two templating options, template and anchorSetup.

An example
            var setupOption = {
    template: '',
    anchorSetup: [
        {
            backgroundColor: "#dc767d",
            label: "ScrollMenu.js",
            className: "test"
            },
        {
            backgroundColor: "#36d278",
            label: "Demos"
            },
        {
            backgroundColor: "#22cfc6",
            label: "Custom Scroll Hooks",
            template : '<%= label %>'
            }]
        };
        
        var scrollMenu  = ScrollMenu(setupOption);
        

template

template option allows you to create a template for each menu in which data are inserted from corresponding anchor setup object.
Templates can be global to all menus of a scrollmenu, or can be specific to single menu if provides inside anchor setup object (as fone in the third item of anchorSetup array)
ScrollMenu uses Micro-Templating by John Resig. Check http://ejohn.org/blog/javascript-micro-templating/ link to see how to use micro templating.

anchorSetup

anchorSetup is array of setup objects which has one to one mapping with respective anchors at same index.
anchorSetup holds data for the menu templates, and some predefined data like backgroundColor (background color for each menu) and className (A specific class for particular menu).
anchorSetup also holds callbacks(if required) like onhover, onhoverOut and onscrollToSection so some events/callbacks can be handled differently for a particular menu. See detail on callbacks

Options

Syntax
                    var myScrollMenu = ScrollMenu({
                        menuType : 'horizontal',
                        anchorSetup : [\*setup object*/]
                    });
                
Option Allowed Value Default Description
sectionClass string section Class to identify sections in page.
menuType vertical / horizontal / horizontal-menu vertical Defines menu type, see detail in Types of menu.
appendTo selector string / jquery object / dom elememt container Tells where to append scrollMenu, by default scrollMenu is appended on container.
animateOnScroll boolean true If true scrolls with animation.
animationDuration integer 600 Duration of animation in scroll.
nativeScroll boolean true If true uses native scroll. Set it to false when you are custom scroll plugin. See Custom Scroll Hooks for detail.
scrollbarVisible boolean false If false hides the native scrollbars.
scrollAnchorSpacing integer 10 Defines spacing between two anchors.
anchorSetup array of setup object null A array of setup objects to template anchors and menu. See templating menu and anchor setup for detail.

Callbacks

You can pass a callback as option or inside anchor setup object if you want that callback specific to one anchor.

Syntax
                       var myScrollMenu = ScrollMenu({
                        onhover : function(e,data){
                                //here this will point to hovered anchor dom
                            }
                        });
                        
                        /* or */
                         var myScrollMenu = ScrollMenu({
                            anchorSetup : [{
                               onhover : function(e,data){
                                //here this will point to hovered anchor dom
                                }
                            },
                            /** other anchors setup object **/
                            ]
                        });
                    

Inside a callback this points to anchor element through which its been fired.
data parameter is a object which contains following information.

  • index :Index of an anchor through which callback is triggered.
  • anchor :Anchor element through which callback is triggered.
  • section :Section element corresponding to anchor.
  • anchorOptions :Setup option for the anchor through which callback is triggered.

callback parameters Description
onhover e(Event),data(Object) Triggers when an anchor is hovered.
onhoverOut e(Event),data(Object) Triggers when mouse leaves an anchor.
onscrollToSection data(Object) Triggers when scrolled to a section(after animation) by clicking an anchor or calling scrollToSection method.
menuMod data(Object) Triggers after anchors are added on page. It can be used to do exta modification through javascript to menu/anchors after its added on page.

Methods

ScrollMenu provides some methods to interact with menu.

                    //Consider myScrollMenu instance for all below codes
                    var myScrollMenu = ScrollMenu('#container');
                

scrollTop()

As ScrollMenu do some transformation on dom structure, you will need scrollTop method to get scrollTop position at a given time.

Example :
                    var currentTop = myScrollMenu.scrollTop();
                    /** will retrun scrolltop position in int like 300 **/
                

scrollTo(top [,animate] [,callback])

Scroll to specified pixels. This method accepts three parameter.

  • top (integer):Top scroll position where you want to scroll it.
  • animate (optional):A boolean to tell weather to scroll with animation. This will be honored only if animateOnScroll option is set to true.
  • callback (optional):A callback function which will be triggered after scroll is done.

Example :
                    myScrollMenu.scrollTop(300,true,function(){
                        console.log('Scroll is done');
                    });
                

scrollToSection(section [,animate] [,callback])

Scroll to specified section. This method accepts three parameter.

  • section :It can be index of section, a selector string, section element or jquery object. This method will scroll to top of the specified section.
  • animate (optional):A boolean to tell weather to scroll with animation. This will be honored only if animateOnScroll option is set to true.
  • callback (optional):A callback function which will be triggered after scroll is done.

Example :
                    myScrollMenu.scrollToSection(3,true,function(){
                        console.log('Scroll is done');
                    });
                

getIndexData(index)

This method will return a object containing info about anchor, section and anchorOptions for the specified index

Example :
                    var data = myScrollMenu.getIndexData(2);
                    /**
                    data will be
                    {
                        anchor : anchorDomElm,
                        section : sectionDomElm,
                        anchorOption : anchorSetupOption
                    }
                    **/
                

refresh()

This method is required to refresh ScrollMenu to update anchor size when container or scrollHeght is changed. See detail in refreshing scrollmenu section

destroy()

This method is used to destroy ScrollMenu instance

Example :
                    myScrollMenu.destroy();
                    myScrollMenu = null; //set instance to null so  instance object can be garbage collected.
                

Refreshing plugin

ScrollMenu relies on height and scroll height(content height) of container, which is calculated when ScrollMenu is initiated. But later on if there is any change to height or scroll height(content height) we need to inform ScrollMenu, so it can readjust things.
To achieve this we need refresh method. refresh method should be called after dom manipulation or css change which is causing change in height or scrollHeight.
The best time to call refresh method after maipulation is when browser has done rendering the changes, so it is adivised to wrap refresh method in setTimeout

Example :
                    /** do some dom manipulation **/
                    /** then **/
                    setTimeout(function(){
                        myScrollMenu.refresh(); /** this will be called when browser is done rendering changes
                    },0);
                

Although setTimeout with 0 sec works most of the time, but it may require to increase the time depending on manipulation. For safer side keep it 200 or 300.

Getting Scroll Element

When you are not using any custom scrollbar plugin, in order to hide browser scrollbar, plugin wraps content of wrapper element to one more div, this removes scroll events and methods from the wrapper, so any scroll event or scroll method will not work with wrapper.

To get the scrolling element you can check scrollElm property of ScrollMenu instance and assign all events and use methods on that element.

Example :
                var scrollElm = myScrollMenu.scrollElm;
                //assiging event
                scrollElm.on('scroll',function(){
                    /*** Do something on scroll ***/
                });
                
                var scrollTop = scrollElm.scrollTop();
            

Note : This is required only when you are not using any custom scroll plugin. If you are using any scroll plugin, you can use there api for events and methods.

Creating hooks for custom scroll plugins

ScrollMenu relay on native scroll, but it can be hooked easily with any custom scroll plugins. There is hook provided for two popular custom scroll plugin, but you can create your own following shown pattern. You can also submit hook if you feel it can help others.

IScroll.js hook

function IScrollMenu(container, scrollMenuOptions, iScrollOptions){

    //modify scrollMenuOptions and iScrollOptions so they can work together
    scrollMenuOptions = scrollMenuOptions || {}; iScrollOptions = iScrollOptions || {}; scrollMenuOptions.nativeScroll = false; iScrollOptions.probeType = 3;

    //initiate both plugins and keep there isntance to return
    var iScrollInst = new IScroll(container, iScrollOptions),
        scrollMenuInst = ScrollMenu(container, scrollMenuOptions);


    //hook scrollTo method
    scrollMenuInst._scrollTo = function (top, duration,callback) {
        iScrollInst.scrollTo(0, -top, duration);
        setTimeout(callback,duration); //as srollTo method does not support callback, wrap it on set timeout 
    }

    //hook scrollTop method
    scrollMenuInst.scrollTop = function () {
        return -iScrollInst.y;
    }

    //hook _scrollHeight method
    scrollMenuInst._scrollHeight = function () {
        return this.container.children().height();
    }


    //hook onScroll event
    iScrollInst.on('scroll', function () {
        scrollMenuInst.onScroll();
    });

    //initiate a onScroll event to set a proper top position
    scrollMenuInst.onScroll();

    //return instance
    return {
        scrollMenu: scrollMenuInst,
        iScroll: iScrollInst
    }
}                
            

As shown on above example, creating a hook for your custom scrollbar plugins requires following steps

  1. Create a hooking function like IScrollMenu.
  2. Update plugin specific options so that both can run together. You must set nativeScroll to false for scrollmenu plugin.
  3. Instantiate scrollmenu plugin and custom scroll plugin.
  4. Update _scrollTo method of scrollmenu instance, so that it will consume your custom scroll's scrollTo (or some similiar) method.
  5. Update _scrollTop method of scrollmenu, so that it will check custom scroll plugin for scrollTop position.
  6. Listen on scroll event of your custom scroll plugin and call ScrollMenu's _onScroll method.
  7. Initiate _onScroll method once to set a proper scroll top position.
  8. Return scrollMenu and your custrom scroll instance so it can be used outside.