This website uses cookies to personalise ads and to analyse traffic ok
web design

Page scroll to id with mousewheel and keyboard

Code sample which should scroll between page sections created with Page scroll to id plugin, using the mouse-wheel and keyboard arrows.

In order to scroll between page sections via mouse-wheel and/or keyboard you’d normally need custom javascript code made specifically for your site layout/markup but I’ve created a more generic script that works along Page scroll to id plugin. The script uses a special plugin class (_mPS2id-h) in order to work independently from most layouts. This class is related to plugin’s highlight feature, meaning that it should work in most cases.

Script for WordPress

“Page scroll to id” WordPress plugin version 1.6.7 or greater must be installed and activated on your site.

After you create your page(s) target sections, edit your theme’s or child-theme’s functions.php and paste the following code

/* 
---------------------------------------- 
"Page scroll to id" with mousewheel and keyboard custom script
The following requires "Page scroll to id" WordPress plugin version 1.6.7 or greater 
---------------------------------------- 
*/

//----- SETUP -----

//set the options for the mousewheel scrolling 

function ps2id_mousewheel_options($opt){
  $opts = array(
        //set the ids of pages or posts that you want the mousewheel functionality to be enabled 
        //and set the target sections URLs for each of your sections of each page
        'ps2id_mousewheel_pages' => array( 
            //page with id 1 and its target sections URLs
            '1' => array(
                //page mousewheel sections URLs (e.g. #section-1 or http://site.com/#section-1 or /page/#section-1)
                '#section-1', 
                '#section-2', 
                '#section-3', 
                '#section-4', 
                '#section-5', 
            ),
            //page with id 2 and its target sections URLs
            '2' => array(
                //page mousewheel sections URLs
                '#section-1', 
                '#section-2', 
            ),
        ),
        //set the default target sections URLs
        'ps2id_mousewheel_default_sections' => array( 
            '#section-1',
            '#section-2', 
        ),
        //Special options for the mouse-wheel smooth scrolling (these overwrite the ones in plugin settings)
        //Scroll type/easing
        'ps2id_mousewheel_scroll_easing' => "easeOutQuint",
        //Scroll duration (in milliseconds)
        'ps2id_mousewheel_scroll_duration' => 1000,
        //Keep the current element highlighted until the next one comes into view (this is needed if the page has non-adjacent sections, i.e. when not all sections are next to one another)
        'ps2id_mousewheel_keep_highlight_until_next' => true,
        //Allow only one highlighted element at a time (should be disabled when $ps2id_mousewheel_keep_highlight_until_next is set to true)
        'ps2id_mousewheel_force_single_highlight' => false,
        //Append the clicked link’s hash value (e.g. #id) to browser’s URL/address bar (this should normally be disabled for better UX)
        'ps2id_mousewheel_append_hash' => false
  );
  $r = (isset($opt) && !empty($opt)) ? $opts[$opt] : $opts;
  return $r;
}

function ps2id_mw_condition($pages_arr){
  //set the condition for the mousewheel functionality 
  //add the WordPress conditional tags you want (https://codex.wordpress.org/Conditional_Tags)
  return is_single( $pages_arr ) || is_page( $pages_arr )
         //|| is_category() //example: uncomment to enable for categories (with the default target sections URLs set in ps2id_mousewheel_default_sections option)
         //|| is_home() //example: uncomment to enable for homepage (with the default target sections URLs set in ps2id_mousewheel_default_sections option)
    ;
}
  
//----- HTML -----

add_action('wp_footer', 'ps2id_mw_html');

function ps2id_mw_html(){
?>
    <?php if(class_exists('malihuPageScroll2id')) : ?>
        <?php
        $pages_arr = ps2id_mw_get_pages();
        $page_id = get_queried_object_id();
        $sections_arr = is_singular() && in_array($page_id, $pages_arr) ? ps2id_mousewheel_options('ps2id_mousewheel_pages')[$page_id] : ps2id_mousewheel_options('ps2id_mousewheel_default_sections');
        ?>
        <?php if(ps2id_mw_condition($pages_arr)) : ?>
            <?php if(!is_null($sections_arr)) : ?>
                <div id="ps2id-mw-sections-bullets">
                <?php 
                foreach($sections_arr as $section){
                    ?>
                    <a href="<?php echo $section; ?>" class="ps2id-mw-section-bullet"></a>
                    <?php
                }
                ?>
                </div>
            <?php endif; ?>
            <style>
                body{ -ms-touch-action: none; touch-action: none; } /* optional for touch/pointer events */

                /* aside bullets section */
                    #ps2id-mw-sections-bullets{
                    position: fixed;
                    right: 2em;
                    height: auto;
                    top: 50%;
                    transform: translateY(-50%);
                    z-index: 2;
                }

                /* aside bullets */
                .ps2id-mw-section-bullet{
                    display: block;
                    position: relative;
                    width: 1.5em;
                    height: 1.5em;
                    border-radius: 100%;
                    margin: 0 auto;
                    opacity: .6;
                }

                .ps2id-mw-section-bullet::before{
                    content: "";
                    display: block;
                    position: absolute;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    left: 0;
                    margin: .4em;
                    border-radius: 100%;
                    border: 1px solid;
                }

                .ps2id-mw-section-bullet:hover, 
                .ps2id-mw-section-bullet.mPS2id-highlight:not(.mPS2id-highlight-first):not(.mPS2id-highlight-last), 
                .ps2id-mw-section-bullet.mPS2id-highlight-first{
                    opacity: 1;
                }
            </style>
        <?php endif; ?>
    <?php endif; ?>
<?php
};

//----- Javascript -----

add_action( 'wp_enqueue_scripts', 'ps2id_special_params', 1 );

function ps2id_special_params(){
    if(class_exists('malihuPageScroll2id')){
        $pages_arr = ps2id_mw_get_pages();
        if(ps2id_mw_condition($pages_arr)) : 
            wp_register_script( 'page-scroll-to-id-mw-js-init', '', array(), '0.0.1', false );
            wp_enqueue_script( 'page-scroll-to-id-mw-js-init' );
            wp_add_inline_script( 'page-scroll-to-id-mw-js-init', 'window.ps2id_special_params={
                highlightSelector: ".ps2id-mw-section-bullet", //mouse-wheel script highlight selector
                scrollEasing: "'.ps2id_mousewheel_options('ps2id_mousewheel_scroll_easing').'", //set a more fitting scroll easing for mousewheel smooth scrolling
                scrollSpeed: '.ps2id_mousewheel_options('ps2id_mousewheel_scroll_duration').', //set a more fitting scrolling duration for mousewheel smooth scrolling
                keepHighlightUntilNext: "'.json_encode(ps2id_mousewheel_options('ps2id_mousewheel_keep_highlight_until_next')).'", //this is needed if the page has non-adjacent sections (i.e. when not all sections are next to one another)
                forceSingleHighlight: "'.json_encode(ps2id_mousewheel_options('ps2id_mousewheel_force_single_highlight')).'", //should be disabled when keepHighlightUntilNext is enabled
                appendHash: "'.json_encode(ps2id_mousewheel_options('ps2id_mousewheel_append_hash')).'" //should normally be disabled for better UX
            };');
        endif;
    }
}

add_action( 'wp_enqueue_scripts', 'ps2id_mw_js', 99 );

function ps2id_mw_js(){
    if(class_exists('malihuPageScroll2id')){
        $pages_arr = ps2id_mw_get_pages();
        if(ps2id_mw_condition($pages_arr)) : 
            if(PS2ID_MINIFIED_JS){
                $deps = array('jquery','page-scroll-to-id-mw-js-init','page-scroll-to-id-plugin-script');
            }else{
                $deps = array('jquery','page-scroll-to-id-mw-js-init','page-scroll-to-id-plugin-init-script','page-scroll-to-id-plugin-script');
            }
            wp_register_script( 'page-scroll-to-id-mw-js', '', $deps, '0.0.1', true );
            wp_enqueue_script( 'page-scroll-to-id-mw-js' );
            wp_add_inline_script( 'page-scroll-to-id-mw-js', '(function($){
                $(window).on("load",function(){
            
                    var doc=$(document),
                        mPS2idData=doc.data("mPS2id"),
                        mPS2idExt;
                
                    if(!mPS2idData){
                        console.log("Error: \'Page scroll to id\' plugin not present or activated. Please run the code after plugin is loaded.");
                        return;
                    }

                    if(!$("._mPS2id-t").length) return;
                
                    doc.data("mPS2idExtend",{
                        selector: "._mPS2id-h",
                        currentSelector: function(){
                            return this.index($(".mPS2id-highlight-first").length ? $(".mPS2id-highlight-first") : $(".mPS2id-highlight").length ? $(".mPS2id-highlight") : $(".mPS2id-wheel-init"));
                        },
                        target: function(){
                            var curr=$(".mPS2id-target-first").length ? $(".mPS2id-target-first") : $(".mPS2id-target").length ? $(".mPS2id-target") : $(".mPS2id-clicked").length ? $("#"+$(".mPS2id-clicked").attr("href").split("#")[1]) : false;
                            if(!curr.length){
                                //if no current target exists, get the next and previous closest sections
                                var max=999999999,
                                    min=-999999999;
                                $("._mPS2id-t").each(function(){
                                    var pos=mPS2idData.layout==="horizontal" ? this.getBoundingClientRect().left : this.getBoundingClientRect().top;
                                    if(pos < 0 && pos > min){
                                        min=pos; 
                                        curr=$("._mPS2id-t[data-psid-wheel-section=\'"+($(this).data("psid-wheel-section")+1)+"\']");
                                    }else if(pos > 0 && pos < max){
                                        max=pos; 
                                        curr=$("._mPS2id-t[data-psid-wheel-section=\'"+($(this).data("psid-wheel-section")-1)+"\']");
                                    }
                                });
                                $("._mPS2id-h[data-psid-wheel-link=\'"+curr.data("psid-wheel-section")+"\']").addClass("mPS2id-wheel-init");
                            }
                            return [
                                $("._mPS2id-t[data-psid-wheel-section=\'"+(curr.data("psid-wheel-section")-1)+"\']"), //previous target
                                curr, //current target
                                $("._mPS2id-t[data-psid-wheel-section=\'"+(curr.data("psid-wheel-section")+1)+"\']"), //next target
                            ];
                        },
                        needScroll: function(dir){
                            if($("html,body").is(":animated")) return;
                            if(dir > 0){ //scrolled fw
                                var el=mPS2idExt.target.call()[2][0]; //next adjacent target
                                if(mPS2idData.layout==="horizontal"){
                                    return el ? el.getBoundingClientRect().left > (window.innerWidth || document.documentElement.clientWidth) : true; //next target is after viewport
                                }else{
                                    return el ? el.getBoundingClientRect().top > (window.innerHeight || document.documentElement.clientHeight) : true; //next target is below viewport
                                }
                            }else if(dir < 0){ //scrolled bw
                                var el=mPS2idExt.target.call()[0][0]; //previous adjacent target
                                if(mPS2idData.layout==="horizontal"){
                                    return el ? el.getBoundingClientRect().right < 0 : true; //previous target is before viewport
                                }else{
                                    return el ? el.getBoundingClientRect().bottom < 0 : true; //previous target is above viewport
                                }
                            }
                        },
                        input:{
                            y: null,
                            x: null
                        },
                        i: null,
                        time: null,
                        debounce:{
                            prevTime: 0
                        },
                        support:{
                            wheel: false
                        }
                    }).on("ps2id-scrollSection",function(e,dlt,i){
                        var sel=$(mPS2idExt.selector);
                        if(!$("html,body").is(":animated")){
                            if(!i) i=mPS2idExt.currentSelector.call(sel);
                            if(!(i===0 && dlt>0) && !(i===sel.length-1 && dlt<0)) sel.eq(i-dlt).trigger("click.mPS2id");
                        }
                    }).on("keydown",function(e){ //keyboard
                        var code=e.keyCode ? e.keyCode : e.which,
                            keys=$(this).data("mPS2id").layout==="horizontal" ? [37,39] : [38,40];
                        if(code===keys[0] || code===keys[1]){
                            if(!mPS2idExt.needScroll((code > 38 ? 1 : -1))){ //check if normal scrolling is needed to reach adjacent targets
                                if($(mPS2idExt.selector).length) e.preventDefault();
                                $(this).trigger("ps2id-scrollSection",(code===keys[0] ? 1 : -1));
                            }
                        }
                    })
                    //touch events (remove the following code if you don\'t want to apply the touch functionality)
                    .on("pointerdown touchstart",function(e){ //touch (optional)
                        var o=e.originalEvent;
                        if(o.pointerType==="touch" || e.type==="touchstart"){
                            var y=o.screenY || o.changedTouches[0].screenY;
                            mPS2idExt.input.y=y;
                            if($(this).data("mPS2id").layout==="horizontal"){
                                var x=o.screenX || o.changedTouches[0].screenX;
                                mPS2idExt.input.x=x;
                            }
                            mPS2idExt.time=o.timeStamp;
                            mPS2idExt.i=mPS2idExt.currentSelector.call($(mPS2idExt.selector));
                        }
                    }).on("pointerup touchend",function(e){
                        var o=e.originalEvent;
                        if(o.pointerType==="touch" || e.type==="touchend"){
                            var y=o.screenY || o.changedTouches[0].screenY,
                                diff=mPS2idExt.input.y-y,
                                time=o.timeStamp-mPS2idExt.time,
                                i=mPS2idExt.currentSelector.call($(mPS2idExt.selector));
                            if($(this).data("mPS2id").layout==="horizontal"){
                                var x=o.screenX || o.changedTouches[0].screenX,
                                    diff=mPS2idExt.input.x-x;
                            }
                            if(Math.abs(diff)<2) return;
                            var _switch=function(){
                                return time<200 && i===mPS2idExt.i;
                            };
                            var dir=diff > 0 ? 1 : -1;
                            if(time < 500 && Math.abs(diff) > 50) $(this).trigger("ps2id-scrollSection",[(diff>0 && _switch() ? -1 : diff<0 && _switch() ? 1 : 0),(_switch() ? mPS2idExt.i : i)]);
                        }
                    })
                    // -----
                    .on("ps2id-wheel-init",function(){
                        //script initialization
                        mPS2idExt=$(this).data("mPS2idExtend");
                        $("._mPS2id-t").each(function(index){
                            $(this).attr("data-psid-wheel-section",index);
                        });
                        $("._mPS2id-h").each(function(index){
                            $(this).attr("data-psid-wheel-link",index);
                        });
                        //vanilla js mousewheel event (https://github.com/jquery/jquery/issues/2871)
                        document.addEventListener(\'wheel\', wheel, {passive: false}, false);
                        document.addEventListener(\'mousewheel\', wheel, {passive: false}, false);
                        document.addEventListener(\'DOMMouseScroll\', wheel, {passive: false}, false);
                        function wheel(e){
                            if(e.type == "wheel"){
                                mPS2idExt.support.wheel = true;
                            }else if(mPS2idExt.support.wheel){
                                return;
                            }
                            if(!mPS2idExt.needScroll((mPS2idData.layout==="horizontal" ? e.deltaX : e.deltaY))){ //check if normal scrolling is needed to reach adjacent targets
                                if($(mPS2idExt.selector).length) e.preventDefault();
                                if((mPS2idData.layout==="vertical" && e.deltaY==-0) || (mPS2idData.layout==="horizontal" && e.deltaX==-0)) return;
                                //trackpad fix (https://stackoverflow.com/a/26514147)
                                var curTime=new Date().getTime();
                                if(typeof mPS2idExt.debounce.prevTime !== "undefined"){
                                    if((curTime-mPS2idExt.debounce.prevTime)>200) doc.trigger("ps2id-scrollSection",((e.detail<0 || e.wheelDelta>0 || e.deltaY<0 || e.deltaX<0) ? 1 : -1));
                                }
                                mPS2idExt.debounce.prevTime=curTime;
                            }
                        };
                    }).trigger("ps2id-wheel-init");
                });

            })(jQuery);');
        endif;
    }
}

function ps2id_mw_get_pages(){
    //get pages ids as array
    $pages_arr = array();
    foreach(ps2id_mousewheel_options('ps2id_mousewheel_pages') as $k => $v) {
        $pages_arr[] = $k;
    }
    return $pages_arr;
}
/* ---------------------------------------- */

Edit ps2id_mousewheel_options function in the code above to setup the pages or posts that you want the mousewheel functionality to be enabled and the target sections URLs for each page. For example, the code below will enable the mousewheel functionality on the posts or pages with id 25, 148 and 3. For each post/page we add its sections URLs:

'ps2id_mousewheel_pages' => array( 
    '25' => array(
        //page mousewheel sections URLs (e.g. #section-1 or http://site.com/#section-1 or /page/#section-1)
        '#section-1', 
        '#section-2', 
        '#section-3', 
        '#section-4', 
        '#section-5', 
    ),
    '148' => array(
        //page mousewheel sections URLs
        '#section-1', 
        '#section-2', 
        '#section-3', 
        '#section-4', 
    ),
    '3' => array(
        //page mousewheel sections URLs
        '#section-1',
        '#section-2', 
        '#section-3', 
        '#section-4', 
        '#section-5', 
        '#section-6', 
        '#section-7', 
        '#section-8', 
    ),
),

Add as many pages as you want 😉

Add the default target sections URLs for pages like homepage, category, archive etc.:

'ps2id_mousewheel_default_sections' => array( 
    '#section-1',
    '#section-2', 
    '#section-3', 
)

Optionally set the condition for the mousewheel functionality in ps2id_mw_condition function:

return is_single( $pages_arr ) || is_page( $pages_arr )
       //|| is_category() //example: uncomment to enable for categories (with the default target sections URLs set in ps2id_mousewheel_default_sections option)
       //|| is_home() //example: uncomment to enable for homepage (with the default target sections URLs set in ps2id_mousewheel_default_sections option)
       ;

You may also want to set few specific plugin option for these pages. These options will overwrite the ones in plugin settings:

//Scroll type/easing
'ps2id_mousewheel_scroll_easing' => "easeOutQuint",
//Scroll duration (in milliseconds)
'ps2id_mousewheel_scroll_duration' => 1000,
//Keep the current element highlighted until the next one comes into view (this is needed if the page has non-adjacent sections, i.e. when not all sections are next to one another)
'ps2id_mousewheel_keep_highlight_until_next' =>  true,
//Allow only one highlighted element at a time (should be disabled when $ps2id_mousewheel_keep_highlight_until_next is set to true)
'ps2id_mousewheel_force_single_highlight' => false,
//Append the clicked link’s hash value (e.g. #id) to browser’s URL/address bar (this should normally be disabled for better UX)
'ps2id_mousewheel_append_hash' => false

How to disable the script on mobile and touch devices?

To disable the script on mobile/touch devices, remove the part from the comment:

//touch events (remove the following code if you don't want to apply the touch functionality)

to the next:

// -----

Also remove the CSS part:

body{ -ms-touch-action: none; touch-action: none; }

Version 2.0 script

You need 3 steps in order to make this work: Add the HTML (1), set few plugin options to specific values (2) and add the custom javascript for the mousewheel (3).

1.The HTML

Add the HTML and CSS for the bullet indicators, changing the links href/URL to your sections ids

<div id="sections-bullets">
  <a href="#section-1" class="section-bullet"></a>
  <a href="#section-2" class="section-bullet"></a>
  <a href="#section-3" class="section-bullet"></a>
  <a href="#section-4" class="section-bullet"></a>
  <a href="#section-5" class="section-bullet"></a>
  <a href="#section-6" class="section-bullet"></a>
  <a href="#section-7" class="section-bullet"></a>
</div>
body{ -ms-touch-action: none; touch-action: none; } /* optional for touch/pointer events */

/* aside indicators */
#sections-bullets{
  position: fixed;
  right: 2em;
  height: auto;
  top: 50%;
  transform: translateY(-50%);
}

.section-bullet{
  display: block;
  position: relative;
  width: 9px;
  height: 9px;
  border-radius: 100%;
  background: #fff;
  margin: 12px auto;
  opacity: .6;
}

.section-bullet:hover, .section-bullet.mPS2id-highlight{
  opacity: 1;
  background: #e6842c;
}

Change the CSS styling to your liking. To disable the script on mobile/touch devices, remove the touch-action css rule in the CSS above.

2.Plugin function call and options

You need to set a few specific options in order for the mousewheel script to work properly. You mainly need to set the highlightSelector option to "#sections-bullets a" and enable keepHighlightUntilNext. You should also set the scroll easing option parameter to a value like "easeOutQuint", "easeOutQuart" etc.:

<script>
    (function($){
        $(window).on("load",function(){
            $("a[rel='m_PageScroll2id']").mPageScroll2id({
                highlightSelector: "#sections-bullets a",
                keepHighlightUntilNext: true,
                scrollEasing:"easeOutQuint",
                scrollSpeed:1200
            });
        });
    })(jQuery);
</script>

3.The script

The following script should be placed after Page scroll to id plugin files and function call.

<script>
    (function($){
      $(window).on("load",function(){
  
        var doc=$(document),
            mPS2idData=doc.data("mPS2id"),
            mPS2idExt;
  
        if(!mPS2idData){
          console.log("Error: 'Page scroll to id' plugin not present or activated. Please run the code after plugin is loaded.");
          return;
        }

        if(!$("._mPS2id-t").length) return;
  
        doc.data("mPS2idExtend",{
          selector: "._mPS2id-h",
          currentSelector: function(){
            return this.index($(".mPS2id-highlight-first").length ? $(".mPS2id-highlight-first") : $(".mPS2id-highlight").length ? $(".mPS2id-highlight") : $(".mPS2id-wheel-init"));
          },
          target: function(){
            var curr=$(".mPS2id-target-first").length ? $(".mPS2id-target-first") : $(".mPS2id-target").length ? $(".mPS2id-target") : $(".mPS2id-clicked").length ? $("#"+$(".mPS2id-clicked").attr("href").split("#")[1]) : false;
            if(!curr.length){
              //if no current target exists, get the next and previous closest sections
              var max=999999999,
                  min=-999999999;
              $("._mPS2id-t").each(function(){
                var pos=mPS2idData.layout==="horizontal" ? this.getBoundingClientRect().left : this.getBoundingClientRect().top;
                if(pos < 0 && pos > min){
                  min=pos; 
                  curr=$("._mPS2id-t[data-psid-wheel-section='"+($(this).data("psid-wheel-section")+1)+"']");
                }else if(pos > 0 && pos < max){
                  max=pos; 
                  curr=$("._mPS2id-t[data-psid-wheel-section='"+($(this).data("psid-wheel-section")-1)+"']");
                }
              });
              $("._mPS2id-h[data-psid-wheel-link='"+curr.data("psid-wheel-section")+"']").addClass("mPS2id-wheel-init");
            }
            return [
              $("._mPS2id-t[data-psid-wheel-section='"+(curr.data("psid-wheel-section")-1)+"']"), //previous target
              curr, //current target
              $("._mPS2id-t[data-psid-wheel-section='"+(curr.data("psid-wheel-section")+1)+"']"), //next target
            ];
          },
          needScroll: function(dir){
            if($("html,body").is(":animated")) return;
            if(dir > 0){ //scrolled fw
              var el=mPS2idExt.target.call()[2][0]; //next adjacent target
              if(mPS2idData.layout==="horizontal"){
                return el ? el.getBoundingClientRect().left > (window.innerWidth || document.documentElement.clientWidth) : true; //next target is after viewport
              }else{
                return el ? el.getBoundingClientRect().top > (window.innerHeight || document.documentElement.clientHeight) : true; //next target is below viewport
              }
            }else if(dir < 0){ //scrolled bw
              var el=mPS2idExt.target.call()[0][0]; //previous adjacent target
              if(mPS2idData.layout==="horizontal"){
                return el ? el.getBoundingClientRect().right < 0 : true; //previous target is before viewport
              }else{
                return el ? el.getBoundingClientRect().bottom < 0 : true; //previous target is above viewport
              }
            }
          },
          input:{
            y: null,
            x: null
          },
          i: null,
          time: null,
          debounce:{
            prevTime: 0
          },
          support:{
            wheel: false
          }
        }).on("ps2id-scrollSection",function(e,dlt,i){
          var sel=$(mPS2idExt.selector);
          if(!$("html,body").is(":animated")){
            if(!i) i=mPS2idExt.currentSelector.call(sel);
            if(!(i===0 && dlt>0) && !(i===sel.length-1 && dlt<0)) sel.eq(i-dlt).trigger("click.mPS2id");
          }
        }).on("keydown",function(e){ //keyboard
          var code=e.keyCode ? e.keyCode : e.which,
            keys=$(this).data("mPS2id").layout==="horizontal" ? [37,39] : [38,40];
          if(code===keys[0] || code===keys[1]){
            if(!mPS2idExt.needScroll((code > 38 ? 1 : -1))){ //check if normal scrolling is needed to reach adjacent targets
              if($(mPS2idExt.selector).length) e.preventDefault();
              $(this).trigger("ps2id-scrollSection",(code===keys[0] ? 1 : -1));
            }
          }
        })
        //touch events (remove the following code if you don't want to apply the touch functionality)
        .on("pointerdown touchstart",function(e){ //touch (optional)
          var o=e.originalEvent;
          if(o.pointerType==="touch" || e.type==="touchstart"){
            var y=o.screenY || o.changedTouches[0].screenY;
            mPS2idExt.input.y=y;
            if($(this).data("mPS2id").layout==="horizontal"){
              var x=o.screenX || o.changedTouches[0].screenX;
              mPS2idExt.input.x=x;
            }
            mPS2idExt.time=o.timeStamp;
            mPS2idExt.i=mPS2idExt.currentSelector.call($(mPS2idExt.selector));
          }
        }).on("pointerup touchend",function(e){
          var o=e.originalEvent;
          if(o.pointerType==="touch" || e.type==="touchend"){
            var y=o.screenY || o.changedTouches[0].screenY,
                diff=mPS2idExt.input.y-y,
                time=o.timeStamp-mPS2idExt.time,
                i=mPS2idExt.currentSelector.call($(mPS2idExt.selector));
            if($(this).data("mPS2id").layout==="horizontal"){
              var x=o.screenX || o.changedTouches[0].screenX,
                  diff=mPS2idExt.input.x-x;
            }
            if(Math.abs(diff)<2) return;
            var _switch=function(){
              return time<200 && i===mPS2idExt.i;
            };
            var dir=diff > 0 ? 1 : -1;
            if(time < 500 && Math.abs(diff) > 50) $(this).trigger("ps2id-scrollSection",[(diff>0 && _switch() ? -1 : diff<0 && _switch() ? 1 : 0),(_switch() ? mPS2idExt.i : i)]);
          }
        })
        // -----
        .on("ps2id-wheel-init",function(){
          //script initialization
          mPS2idExt=$(this).data("mPS2idExtend");
          $("._mPS2id-t").each(function(index){
            $(this).attr("data-psid-wheel-section",index);
          });
          $("._mPS2id-h").each(function(index){
            $(this).attr("data-psid-wheel-link",index);
          });
          //vanilla js mousewheel event (https://github.com/jquery/jquery/issues/2871)
          document.addEventListener('wheel', wheel, {passive: false}, false);
          document.addEventListener('mousewheel', wheel, {passive: false}, false);
          document.addEventListener('DOMMouseScroll', wheel, {passive: false}, false);
          function wheel(e){
            if(e.type == "wheel"){
              mPS2idExt.support.wheel = true;
            }else if(mPS2idExt.support.wheel){
              return;
            }
            if(!mPS2idExt.needScroll((mPS2idData.layout==="horizontal" ? e.deltaX : e.deltaY))){ //check if normal scrolling is needed to reach adjacent targets
              if($(mPS2idExt.selector).length) e.preventDefault();
              if((mPS2idData.layout==="vertical" && e.deltaY==-0) || (mPS2idData.layout==="horizontal" && e.deltaX==-0)) return;
              //trackpad fix (https://stackoverflow.com/a/26514147)
              var curTime=new Date().getTime();
              if(typeof mPS2idExt.debounce.prevTime !== "undefined"){
                if((curTime-mPS2idExt.debounce.prevTime)>200) doc.trigger("ps2id-scrollSection",((e.detail<0 || e.wheelDelta>0 || e.deltaY<0 || e.deltaX<0) ? 1 : -1));
              }
              mPS2idExt.debounce.prevTime=curTime;
            }
          };
        }).trigger("ps2id-wheel-init");
      });
      
    })(jQuery);
</script>

To disable the script on mobile/touch devices, remove the part from the comment:

//touch events (remove the following code if you don't want to apply the touch functionality)

to the next:

// -----

Version 1.0 script

The script should be placed after Page scroll to id plugin files and function call. If you’re using the WordPress version of the plugin, you should place it wherever your theme allows you to add custom javascript or directly in the footer.php template inside a script (<script>...</script>) tag after wp_footer();

The script

(function($){
  $(window).on("load",function(){

    if(!$(document).data("mPS2id")){
      console.log("Error: 'Page scroll to id' plugin not present or activated. Please run the code after plugin is loaded.");
      return;
    }

    $(document).data("mPS2idExtend",{
      selector:"._mPS2id-h",
      currentSelector:function(){
        return this.index($(".mPS2id-highlight-first").length ? $(".mPS2id-highlight-first") : $(".mPS2id-highlight"));
      },
      input:{y:null,x:null},
      i:null,
      time:null
    }).on("scrollSection",function(e,dlt,i){
      var d=$(this).data("mPS2idExtend"),
          sel=$(d.selector);
      if(!$("html,body").is(":animated")){
        if(!i) i=d.currentSelector.call(sel);
        if(!(i===0 && dlt>0) && !(i===sel.length-1 && dlt<0)) sel.eq(i-dlt).trigger("click.mPS2id");
      }
    }).on("keydown",function(e){ //keyboard
      var code=e.keyCode ? e.keyCode : e.which,
          keys=$(this).data("mPS2id").layout==="horizontal" ? [37,39] : [38,40];
      if(code===keys[0] || code===keys[1]){
        if($($(this).data("mPS2idExtend").selector).length) e.preventDefault();
        $(this).trigger("scrollSection",(code===keys[0] ? 1 : -1));
      }
    });

    //mousewheel (https://github.com/jquery/jquery/issues/2871)
    var supportsWheel=false;
    function wheel(e){
      if (e.type == "wheel") supportsWheel = true;
        else if (supportsWheel) return;
      if($($(document).data("mPS2idExtend").selector).length) e.preventDefault();
      $(document).trigger("scrollSection",((e.detail<0 || e.wheelDelta>0 || e.deltaY<0 || e.deltaX<0) ? 1 : -1));
    };
    document.addEventListener('wheel', wheel, {passive: false}, false);
    document.addEventListener('mousewheel', wheel, {passive: false}, false);
    document.addEventListener('DOMMouseScroll', wheel, {passive: false}, false);

  });
})(jQuery);

You can change the selector value to a more specific one if you need. This selector should be your “Page scroll to id” main navigation links, so instead of using simply selector:"._mPS2id-h" you could use for example selector:".menu-item ._mPS2id-h"

Important: Please note that you do not have to add the _mPS2id-h class to your elements. It is added automatically by the plugin. Also note that if you have additional links handled by the plugin (e.g. in addition to your menu links, you have back-to-top, next/previous section links etc. in your page), you might need to set your main (e.g. menu) links selector as the “Highlight selector(s)” in plugin settings (e.g. set the option value to .menu-item a).

The script works best when your sections have the same height (or width for horizontal layouts) as the viewport, which is something that most page layouts with this kind of functionality have.

Extending the script with touch events (optional)

If you want to have the same functionality in touch-devices, you can extend the script above like this:

(function($){
  $(window).on("load",function(){

    if(!$(document).data("mPS2id")){
      console.log("Error: 'Page scroll to id' plugin not present or activated. Please run the code after plugin is loaded.");
      return;
    }

    $(document).data("mPS2idExtend",{
      selector:"._mPS2id-h",
      currentSelector:function(){
        return this.index($(".mPS2id-highlight-first").length ? $(".mPS2id-highlight-first") : $(".mPS2id-highlight"));
      },
      input:{y:null,x:null},
      i:null,
      time:null
    }).on("scrollSection",function(e,dlt,i){
      var d=$(this).data("mPS2idExtend"),
          sel=$(d.selector);
      if(!$("html,body").is(":animated")){
        if(!i) i=d.currentSelector.call(sel);
        if(!(i===0 && dlt>0) && !(i===sel.length-1 && dlt<0)) sel.eq(i-dlt).trigger("click.mPS2id");
      }
    }).on("keydown",function(e){ //keyboard
      var code=e.keyCode ? e.keyCode : e.which,
          keys=$(this).data("mPS2id").layout==="horizontal" ? [37,39] : [38,40];
      if(code===keys[0] || code===keys[1]){
        if($($(this).data("mPS2idExtend").selector).length) e.preventDefault();
        $(this).trigger("scrollSection",(code===keys[0] ? 1 : -1));
      }
    }).on("pointerdown touchstart",function(e){ //touch (optional)
      var o=e.originalEvent,
          d=$(this).data("mPS2idExtend");
      if(o.pointerType==="touch" || e.type==="touchstart"){
        var y=o.screenY || o.changedTouches[0].screenY;
        d.input.y=y;
        if($(this).data("mPS2id").layout==="horizontal"){
          var x=o.screenX || o.changedTouches[0].screenX;
          d.input.x=x;
        }
        d.time=o.timeStamp;
        d.i=d.currentSelector.call($(d.selector));
      }
    }).on("touchmove",function(e){
      if($("html,body").is(":animated")) e.preventDefault();
    }).on("pointerup touchend",function(e){
      var o=e.originalEvent;
      if(o.pointerType==="touch" || e.type==="touchend"){
        var y=o.screenY || o.changedTouches[0].screenY,
            d=$(this).data("mPS2idExtend"),
            diff=d.input.y-y,
            time=o.timeStamp-d.time,
            i=d.currentSelector.call($(d.selector));
        if($(this).data("mPS2id").layout==="horizontal"){
          var x=o.screenX || o.changedTouches[0].screenX,
              diff=d.input.x-x;
        }
        if(Math.abs(diff)<2) return;
        var _switch=function(){
            return time<200 && i===d.i;
          };
        $(this).trigger("scrollSection",[(diff>0 && _switch() ? -1 : diff<0 && _switch() ? 1 : 0),(_switch() ? d.i : i)]);
      }
    });

    //mousewheel (https://github.com/jquery/jquery/issues/2871)
    var supportsWheel=false;
    function wheel(e){
      if (e.type == "wheel") supportsWheel = true;
        else if (supportsWheel) return;
      if($($(document).data("mPS2idExtend").selector).length) e.preventDefault();
      $(document).trigger("scrollSection",((e.detail<0 || e.wheelDelta>0 || e.deltaY<0 || e.deltaX<0) ? 1 : -1));
    };
    document.addEventListener('wheel', wheel, {passive: false}, false);
    document.addEventListener('mousewheel', wheel, {passive: false}, false);
    document.addEventListener('DOMMouseScroll', wheel, {passive: false}, false);

  });
})(jQuery);

You should also add the following rule to your stylesheet:

body{ -ms-touch-action: none; touch-action: none; }

Please note that using such functionality with touch devices can be (very) tricky and might not work exactly the same across all devices, browsers etc. A good way would be to keep such behavior for mouse and keyboard and let touch devices scroll the page normally.

Auto-generating aside bullet indicators (optional)

If you see the script demo, in addition to the main navigation menu, you’ll notice few bullets at the right which act as links and visual indicators of the sections. You can create those by hand or you can use a small function like this:

$("body").append("<div id='sections-bullets' />").find($(document).data("mPS2idExtend").selector).each(function(){
  $("#sections-bullets").append("<a href='"+$(this).attr("href")+"' class='section-bullet' rel='m_PageScroll2id'></a>");
});

This should be placed within the window load function:

(function($){
  $(window).on("load",function(){

    //the script above goes here...

    //still inside window load we add the function that auto-generates the bullets 
    $("body").append("<div id='sections-bullets' />").find($(document).data("mPS2idExtend").selector).each(function(){
      $("#sections-bullets").append("<a href='"+$(this).attr("href")+"' class='section-bullet' rel='m_PageScroll2id'></a>");
    });

  });
})(jQuery);

If you need help or the code customized for some specific layout let me know in the comments or contact me.

 


174 Comments

Post a comment

Comments pages: 1 2

  1. The Real Has Come ! 1. Sezon 14. Bölüm
    Posted on May 7, 2023 at 06:21 Permalink

    Thanks in advance! Best regards, Marcel

    Reply
  2. One Piece 1061. Bölüm
    Posted on May 7, 2023 at 06:20 Permalink

    Great job! Thank you very much!!

    Reply
  3. canlidiziizlesene
    Posted on April 3, 2023 at 03:02 Permalink

    Yes! Very useful tips presented here. Thank you very much.

    Reply
  4. Chris
    Posted on December 6, 2022 at 14:50 Permalink

    hey, there seems to be a major problem on the IMac and the IMac mouse. The scrolling works fine, but every now and then you just get stuck in a section and can’t scroll up or down. Only after clicking it works again, until you get stuck in another section. Does anyone have an idea?

    Reply
  5. Susan
    Posted on December 24, 2020 at 01:00 Permalink

    Hi, thanks a lot for your code. Its working fine but i need more options in menú and only are working well seven, please can you tell me how to add more options to the menu correctly? Im using your demo (horizontal).
    I need 18 items in my nav.
    Thanks!

    Reply
    • malihu
      Posted on December 24, 2020 at 02:48 Permalink

      Hello, 

      Since you have 18 slides, you also need to change the width percentage of each section,  from 14.285% (100/7 in the demo – for 7 sections) to 5.555% (100/18 in your page – for 18 sections). So, change the .horizontal-layout #content section css to: 

      .horizontal-layout #content section {     width: 5.555%;     float: left;     min-height: 100vh; }

      That should do it 😉 

      Reply
      • Susan
        Posted on December 24, 2020 at 12:56 Permalink

        Thank you! It works perfectly!
        I emailed you because I need more help on how to add the .mPS2id-clicked class in menu items when I scroll in other sections, because an option menu is two or three sections on the web. I don’t know if it will be too much or if it can be done with your javascript. Maybe I can do it myself, but I don’t know in which javascritp event I would have to include it. Can you help me again? I’d be doubly grateful but you’ve already saved my life with your code. Thanks a lot!

        Reply
  6. Don Julio
    Posted on October 29, 2020 at 04:23 Permalink

    Great Plugin! I used the script for wordpress and everything seems to be working except for the highlight on the menu. Please let me know if I’ve forgotten something.

    site is –> http://hiqmsp.com

    Thanks!

    Reply
  7. Jiràw
    Posted on May 5, 2020 at 15:45 Permalink

    Hello,

    First, thank you for this amazing tutorial. It’s working fine with my desktop mouse but not in my laptop (trackpad), it jump 2 sections instead of one.
    I tried with your demo website, work’s fine in desktop/laptop.
    Do you have any clues please ?

    Regards.

    Reply
    • Jiràw
      Posted on May 5, 2020 at 15:55 Permalink

      I see that when I scroll very very very slowly with the trackpad it works but no one of the users scroll like that ahah

      Reply
      • malihu
        Posted on May 5, 2020 at 16:39 Permalink

        Hello,

        I have test this on more trackpads than I already have and see if I can come up with an easy solution (e.g. add some timeout to debounce mousewheel).

        Right now, the best thing to do is to increase “Scroll duration” option (especially since you’ve set the “Scroll type” to ease-out).

        Let me know

        Reply
        • Jiràw
          Posted on May 5, 2020 at 20:49 Permalink

          Oh great ! It work ! Thank you man.
          I would like a top menu which coloring with the current section like your demo website !
          Do u have a tutorial for this ? 🙂

          Thanks !

          Reply
          • malihu
            Posted on May 5, 2020 at 23:49 Permalink

            You’re welcome.
            No, I don’t have one. Maybe you could copy/paste the HTML and CSS from the demo and apply it to your site(?)

  8. max
    Posted on April 29, 2020 at 14:33 Permalink

    Hi,
    thank you for your code, it’s really powerful!!!

    I have in issue on my website in this page:
    https://www.unmetroinmeno.com/landing

    whats happens when the content of the page exceeds the full height of the section?

    now, if I scroll to read below, it jumps to next ID

    thanks in advance for your feedback
    best
    max

    Reply
    • max
      Posted on April 29, 2020 at 15:26 Permalink

      I mean “when the content exceed the hieght of the viewport”

      Reply
    • malihu
      Posted on April 29, 2020 at 22:46 Permalink

      Hello,

      Did you add the updated script in your functions.php as shown above?

      Reply
      • max
        Posted on April 29, 2020 at 23:59 Permalink

        Hi malihu,
        yes I insert the main script above in the function.php of my theme, then the script version 1.0 in the footer.php after wp_footer();

        it’s works, but if the dimension of the section is graater than viewport the scrolling doesn’t become normal

        https://www.unmetroinmeno.com/landing/

        can you please help me?

        thanks
        max

        Reply
        • max
          Posted on April 30, 2020 at 00:22 Permalink

          even in your demo
          http://manos.malihu.gr/repository/page-scroll-to-id/demo/ps2id-mousewheel-keyboard-example.html

          if i resize the browser window til to hide a portion of the text, the scroll function doesn’t become normal

          thank you

          Reply
        • malihu
          Posted on April 30, 2020 at 00:47 Permalink

          No, you don’t need script version 1.0. Remove the v1.0 script from your footer.php.

          Add only the code from “Script for WordPress” guide in your functions.php and customize it for your pages. Just follow the instructions above.

          My demo is not WordPress and it’s using the old v1.0 script which does not have this feature.

          Just follow the “Script for WordPress” guide.

          Reply
          • max
            Posted on April 30, 2020 at 10:30 Permalink

            Hi malihu,
            it’s works perfectly!

            brilliant!

            thanks
            max

  9. Sayan Roy
    Posted on April 26, 2020 at 06:54 Permalink

    Hi, Malihu.

    First of all thanks for this beautifully done script. I’ve been scratching my head for a year now but nothing seemed to work perfectly as yours. The only very small hiccup I’m having is perhaps regarding the offset. When I’m using the section buttons on the right, the section is perfectly adjusted to the middle of the screen. But when I’m using mouse scroll, the section is a bit offset. Any ideas what went wrong on my part?

    Website:
    http://younsociety.in

    Reply
    • malihu
      Posted on April 30, 2020 at 03:25 Permalink

      Hi,

      Seems I missed your comment. Do you still need help with this? I checked your page and it seems you’re not using such sections anymore(?)

      Reply
  10. Neha
    Posted on April 8, 2020 at 15:20 Permalink

    Hi Manos,

    Thank you for such great work on this plugin and it works like a charm. However, I do have one query regarding the scroll thing.

    I have implemented scrolling functionality in adjacent sections. But there are certain sections whose height is greater than the viewport height because of more content in it.

    In this scenario, the scrolling behavior is not working as expected.

    Expected behavior: If my viewport height is 630px and section height is 900px. When a user navigates to section, only 1st half i.e. 630px of content should be visible and on another scroll, remaining content i.e. (900 – 630)px should be visible.

    I hope you can assist me to get this resolved?

    Reply
    • malihu
      Posted on April 8, 2020 at 20:15 Permalink

      Hello,

      The script works like this:

      When a section height is greater than the viewport height, scrolling becomes normal until the next section is reached. This is the expected behavior.
      Is this what happens in your case?

      Reply
      • max
        Posted on April 29, 2020 at 15:57 Permalink

        same happens to me:

        https://www.unmetroinmeno.com/landing

        thank you!
        m

        Reply
      • Neha
        Posted on April 29, 2020 at 18:18 Permalink

        Yes, it’s working the same. Scrolling becomes normal

        Reply
        • Neha
          Posted on April 29, 2020 at 18:43 Permalink

          Just an another question as I’m not good at scripting part.
          What changes I need to do if I want to remove mouse wheel scrolling functionality and only keep dots on right hand side.

          Expected Behavior: User should be able to navigate to respective sections via dots but scrolling on the page should be normal.

          Thanks in advance !!

          Reply
          • malihu
            Posted on April 30, 2020 at 00:51 Permalink

            You should only add in your template the HTML and CSS shown here. Nothing else (no js script, no functions.php code etc.).

        • max
          Posted on April 29, 2020 at 22:30 Permalink

          from my side the scrolling doesn’t became normal:
          there are some option to setup the section?
          (example height)

          thanks

          Reply
  11. emanuele
    Posted on March 29, 2020 at 14:52 Permalink

    hi, thanks for your work!

    i’ve got a delay (like in your demo)

    https://www.emanueleparavisi.it/testsite2020asp/

    how can i solve?and how can i disable the scroll effects on mobile devices?

    thanks a lot

    Reply
    • malihu
      Posted on March 29, 2020 at 15:10 Permalink

      Hello,

      I don’t see any delay in your page or my demo. Can you provide more info on the issue?

      To disable the script on mobile, simply remove the code from:

      //touch events (remove the following code if you don\'t want to apply the touch functionality)

      to:

      // -----

      Reply
      • emanuele
        Posted on March 29, 2020 at 16:56 Permalink

        great, thanks for the faster reply,

        in fact i see on imac (with chrome and magic mouse) that the delay problem doesn’t exist,

        i see this problem on my pc (chrome with an old logitech mouse)
        at the first roll the section doesn’t scroll immediately, i’ve to roll the mousewheel 2 times.

        thanks!

        Reply
        • malihu
          Posted on March 29, 2020 at 21:19 Permalink

          I’ve tested your page with 2 mouses (with and without free-scroll) as well as with a Microsoft trackpad on Windows and I don’t have the issue you describe. Maybe it’s something specific with your mouse (e.g. not registering the first wheel notch since it’s old)?

          Reply
          • Emanuele
            Posted on March 29, 2020 at 23:50 Permalink

            yes,
            it’s definitely a problem with my mouse

            thanks!

      • emanuele
        Posted on March 29, 2020 at 17:06 Permalink

        hi, i remove the code, now i can move between section only with the side bar.
        it’s possible to return to the normal site visualization only on mobile view?

        Reply
        • malihu
          Posted on March 29, 2020 at 21:16 Permalink

          Ah yes, you also need to remove the following from the CSS:

          body{ -ms-touch-action: none; touch-action: none; } /* optional for touch/pointer events */

          Reply
          • Emanuele
            Posted on March 29, 2020 at 23:49 Permalink

            great!

            work perfectly, thanks so much, you’re very kind

            Emanuele

  12. Mohamed
    Posted on February 3, 2020 at 17:38 Permalink

    hi malihu

    cool plugin, by the way, thanks.

    so I have an issue with the weel code !!!
    it’s the same on your example :

    http://manos.malihu.gr/repository/page-scroll-to-id/demo/ps2id-mousewheel-keyboard-example.html

    I can’t reach the footer

    Reply
    • malihu
      Posted on February 3, 2020 at 18:39 Permalink

      Hello,

      The current script above is developed to work only on adjacent sections that are the same height as the browser’s viewport (i.e. with very specific content layout).

      This said, you could add a target id on your footer (the same way you’ve done with your other sections) in order to make it work like the rest of your sections.

      I’m currently working on updating the mouse-wheel script so it can work with non-adjacent sections (like in your case) and sections with content that extends the browser’s viewport.
      I’ll also make the script easier to implement via functions.php.

      I’ll publish the updated script, hopefully within next week 😉

      Reply
  13. Chirstoph
    Posted on December 30, 2019 at 00:31 Permalink

    I try to put it into the site like u describe:
    http://b2bo8b5i.myraidbox.de/

    i want to try it firs just with the sektion-1 button.

    i integrated the code with the code-snippet plugin and this code:

    add_action( 'wp_footer', function () { ?> <script> /* Schreiben Sie Ihren JavaScript Code hier */ (function($){ $(window).on("load",function(){ if(!$(document).data("mPS2id")){ console.log("Error: 'Page scroll to id' plugin not present or activated. Please run the code after plugin is loaded."); return; } $(document).data("mPS2idExtend",{ selector:"._mPS2id-h", currentSelector:function(){ return this.index($(".mPS2id-highlight-first").length ? $(".mPS2id-highlight-first") : $(".mPS2id-highlight")); }, input:{y:null,x:null}, i:null, time:null }).on("scrollSection",function(e,dlt,i){ var d=$(this).data("mPS2idExtend"), sel=$(d.selector); if(!$("html,body").is(":animated")){ if(!i) i=d.currentSelector.call(sel); if(!(i===0 && dlt>0) && !(i===sel.length-1 && dlt<0)) sel.eq(i-dlt).trigger("click.mPS2id"); } }).on("keydown",function(e){ //keyboard var code=e.keyCode ? e.keyCode : e.which, keys=$(this).data("mPS2id").layout==="horizontal" ? [37,39] : [38,40]; if(code===keys[0] || code===keys[1]){ if($($(this).data("mPS2idExtend").selector).length) e.preventDefault(); $(this).trigger("scrollSection",(code===keys[0] ? 1 : -1)); } }); //mousewheel (https://github.com/jquery/jquery/issues/2871) var supportsWheel=false; function wheel(e){ if (e.type == "wheel") supportsWheel = true; else if (supportsWheel) return; if($($(document).data("mPS2idExtend").selector).length) e.preventDefault(); $(document).trigger("scrollSection",((e.detail<0 || e.wheelDelta>0 || e.deltaY < 0 || e.deltaX < 0) ? 1 : -1)); }; document.addEventListener('wheel', wheel, {passive: false}, false); document.addEventListener('mousewheel', wheel, {passive: false}, false); document.addEventListener('DOMMouseScroll', wheel, {passive: false}, false); }); })(jQuery); </script>

    but dont know it seems not to work.

    Reply
    • malihu
      Posted on January 1, 2020 at 15:52 Permalink

      Hi,

      I tested your page and mousewheel scrolling works for me. Did you fix it? Do you need help with styling the bullet indicators?

      Reply
  14. Mirco
    Posted on December 21, 2019 at 11:45 Permalink

    Hi there,

    I’m trying to implement this code on a The7 template website https://www.mirconatili.com/comunicazione-marketing-digitali/
    It doesn’t work and, being not so good at coding, I’m here to ask for your help.
    Some clues on what’s going on?

    Thanks in advance, have a nice day.

    Reply
  15. Marcel
    Posted on October 31, 2019 at 17:06 Permalink

    Hi Malihu, thank you for the great work on your plugin (Page scroll to id) and the additional code to jump to id’s rather than scrolling. I’m using your work on a new website (in development) and I’m encountering some issues. The url is http://bed.k-dushi.com/. Jumping to the second section works but then it “get’s stuck”. It isn’t possible to jump to the third section other than the arrow button I included. It also doesn’t jump to the footer. From the last section (before the footer) it jumps back up. Would it be possible to check this out? That would be very much appreciated. Thanks in advance! Best regards, Marcel

    Reply
    • malihu
      Posted on November 3, 2019 at 19:31 Permalink

      I replied to your email last week (not sure if you saw it?). Anyway, here’s a copy:
      —–
      Hello,

      Try this:

      Go to plugin settings and set “Highlight selector(s)” option value to:

      a.vc_icon_element-link

      Save changes and test your page.

      This will make the plugin script to scroll through the the sections defined by your arrow links (i.e #two and #three). You’ll probably need another link like these to point to your section #one so the user can cycle through all 3 sections.
      —–

      Reply
      • Marcel
        Posted on November 11, 2019 at 17:36 Permalink

        Hi Malihu, sorry for my late reaction. I didn’t get your email but also didn’t receive a notification of your reply.. So I only saw it just now.

        I added the class and it works a bit better. But it still doesn’t scroll back to #one although I added a button linking to this id. Also it doesn’t go to the footer. Do I need to give that the id #four (for example) and at a link as well?

        Thanks for your help! 🙂

        Reply
        • malihu
          Posted on November 13, 2019 at 15:08 Permalink

          The 2 buttons you added are a bit different than the arrows (their CSS selector is different), so the “Highlight selector(s)” value we added will not work for them.

          The best way to have one set of elements and still use any type of button you like (or not use any button if you want), is to have a hidden menu somewhere in your page, that users won’t be able to see (but the script will). For example:

          <div id="ps2id-mousewheel-menu" style="display:none"> <a href="#one"></a> <a href="#two"></a> <a href="#three"></a> <a href="#four"></a> </div>

          You could add the above HTML code in your page and in plugin settings change “Highlight selector(s)” option value to:

          #ps2id-mousewheel-menu a

          This way, you could add/remove links (in the HTML code) without affecting how your page looks (i.e. without having to add actual buttons to the page).

          Reply
          • Marcel
            Posted on November 25, 2019 at 15:36 Permalink

            Perfect! It works. Thank you so much!

  16. Abul
    Posted on October 25, 2019 at 13:25 Permalink

    hi, i am using this scrolling feature in my home page but my requirement is i want to use menu with other links bcuz my website is a multipage website , Is it possible to scroll section wise without passing links in the menu? If possible kindly provide me the solution

    Reply
    • malihu
      Posted on October 25, 2019 at 14:59 Permalink

      Hi,

      You can change the “selector” property in the script to match the elements you want. For instance, you could change:

      selector:"._mPS2id-h",

      to:

      selector:".my-links-class",

      Or maybe you could simply create a hidden menu to act as the base for mouse-wheel scrolling. For example:

      <div class="ps2id" style="display:none;"> <a href="#section-1">...</a> <a href="#section-2">...</a> <a href="#section-3">...</a> </div>

      The script will see the above menu, the user won’t.

      Reply
      • abul
        Posted on November 25, 2019 at 11:58 Permalink

        Thanks for help , i have find an alternate solution for this , but problem i m facing now is navigation bullet is not visible after adding the code.

        Reply
        • malihu
          Posted on November 25, 2019 at 12:03 Permalink

          Hi, I replied to your email 🙂
          You need to style the bullets in CSS.

          Reply
  17. Farheen
    Posted on October 16, 2019 at 13:37 Permalink

    Thanks.. it reallty helped me

    Reply
  18. Sophia
    Posted on September 30, 2019 at 02:31 Permalink

    I’ve tried looking through the documentation but I don’t see an answer to this – sorry if it’s been covered.

    When clicking an up arrow image I would like to be taken to the previous section, and when clicking a down arrow image I would like to be taken to the next section. How can I do this?

    I see an example here: http://manos.malihu.gr/repository/page-scroll-to-id/demo/demo.html but don’t see how to do it in the plugin docs.

    Thanks!

    Reply
    • malihu
      Posted on October 2, 2019 at 08:14 Permalink

      The custom script in this post already covers scrolling to the next/previous section via keyboard arrows. To have actual next/previous section links, you’ll need to create them manually. It’s what I did on the demo page you posted.

      The script cannot create such links automatically. You should create a link for each section that points to the next section’s id (same with previous links).

      Reply
  19. [email protected]
    Posted on September 19, 2019 at 19:54 Permalink

    So, I got this to work and it’s great!

    On my macbook touchpad, there is a long delay after it’s swiped to when the scroll starts. Is there a way to make that faster?

    thanks!!!

    Reply
    • malihu
      Posted on September 20, 2019 at 10:33 Permalink

      Does the same delay occur on the demo?

      I don’t have a macbook but when I test the script on my mac (with magic the trackpad) I don’t see any delay.

      Reply
      • [email protected]
        Posted on September 20, 2019 at 15:53 Permalink

        No, it doesn’t! What do you think the issue is?

        http://www.doesntaddup.com/homepage/

        Reply
        • malihu
          Posted on September 21, 2019 at 16:34 Permalink

          I checked the link you posted and it doesn’t use the “Page scroll to id” script (which this post is about).

          The way your page works, the menu animation takes a little time to open/close, so page scrolling needs to wait for all related animations to finish before scrolling the page.

          Reply
          • [email protected]
            Posted on September 26, 2019 at 00:07 Permalink

            Thanks for looking, I switched the page to use an alternate method while I was waiting for your reply, but thank you!

  20. Claire
    Posted on July 9, 2019 at 11:25 Permalink

    Hi malihu

    I am having trouble getting the page to scroll to the sections via mouse wheel.
    Can you please let me know what I am not doing correctly?

    We are using the Noor theme with the WPBakery Page Builder on our site.

    Thanks

    Claire

    Reply
  21. Mingle Basket
    Posted on June 26, 2019 at 10:44 Permalink

    How can i download this full code with html because i have to implement on my website. Please help.

    Reply
    • malihu
      Posted on June 27, 2019 at 12:48 Permalink

      The code for the mousewheel is not a file you upload to your site. You need to edit your existing HTML and add the above code in it in a script tag.

      For example, if you’re using WordPress version of the plugin, edit your theme/child-theme footer.php template and copy/paste the js code after the wp_footer(); function:

      wp_footer(); <script> //code goes here </script>

      Reply
  22. Kristen Mathiasen
    Posted on May 20, 2019 at 20:19 Permalink

    Hi Manos.
    I have followed your guide on this page but can’t seem to get the scroll-function to work with keyboard-arrows.
    I’m using the WordPress-plugin as well and has put the top JS into the footer.
    I have tried with different selectors and targets but to no avail.
    Do you have any idea where I go woring?
    Thank you in advance.

    Kind regards.

    Kristen

    Reply
    • malihu
      Posted on May 20, 2019 at 23:39 Permalink

      Hello Kristen,

      I checked the source of your page and the js script is not there. Not sure how/where you insert it but it’s not loaded in the front-end.

      Reply
      • Kristen
        Posted on June 27, 2019 at 20:59 Permalink

        Hi again Malihu.
        The site crashed shortly after, so I have build it again.
        Now I get the scroll to work but shortly on the frontpage after it stops working. when I check the Chrome browser Console I get the following error:
        [Violation] Forced reflow while executing JavaScript took 60ms
        This error is repeating itself and I think that is the reason the scrollfunction doesn’t work.
        Another question: can I get the keyboard-arrows to work after the last page-scroll (It scrolls 3 times to the 3 #-links I have made – but then the keyboard-arrows doesn’t work any more)

        I hope you can take a look at it and return with a solution.

        Kind regards.

        Kristen

        Reply
  23. CJ
    Posted on April 5, 2019 at 19:54 Permalink

    Hi, as of the latest chrome update, scrolling events are listed as passive by default. That means event.preventDefault() will be ignored on scroll unless another parameter ({ passive: false }); is passed to the event listener.

    Jquery has an open ticket for this and apparently it is hard to implement passing this extra parameter with jquery.

    Chome feature description:
    https://www.chromestatus.com/feature/6662647093133312

    Github open issue:
    https://github.com/jquery/jquery/issues/2871

    This means that the current suggestion for using this plugin on scroll events results in choppy scrolling (because e.preventDefault() is ignored).

    .on("mousewheel DOMMouseScroll",function(e){ //mousewheel if($($(this).data("mPS2idExtend").selector).length) e.preventDefault(); $(this).trigger("scrollSection",((e.originalEvent.detail<0 || e.originalEvent.wheelDelta>0) ? 1 : -1));

    Do you have any suggestion for how rewrite this part as vanilla js, using addEventListener, so that the “passive” parameter can be passed properly?

    Thanks in advance!

    Reply
    • malihu
      Posted on May 9, 2019 at 04:08 Permalink

      Hello,

      Sorry I think I missed your previous message (I get a lot!)

      At the moment there’s no way to do it with jQuery. The only way is to write a vanilla javascript mouse-wheel function.

      Because of the severity of this issue, I updated the code and replaced the jQuery mouse-wheel function with a pure javascript one. This is needed in order to use the passive: false (see the updated code).

      Let me know

      Reply
      • CJ
        Posted on July 4, 2019 at 17:00 Permalink

        Hi Malihu,

        Thank you for providing that updated snippet. Works really well.

        Before I saw that reply, I had managed to work around by doing another vanilla js work around, but I prefer using your solution.

        Reply
    • malihu
      Posted on March 21, 2019 at 20:47 Permalink

      Hi,

      You’ll need to have the section links somewhere in your page (even hidden), because otherwise the script cannot function. You can simply place a div with the links anywhere and hide them via CSS display: none;

      Reply
  24. Tyler K
    Posted on February 3, 2019 at 04:41 Permalink

    Thanks for this plugin, script, and support! I hope you can assist me. I have the plugin installed, but after I put the script into my footer.php, I can no longer scroll with my mouse at all on the site.

    If I use the menu to go to another section on the page, that works fine – but if you scroll down on the mouse, it will bring you always to the top of the page.

    https://testingwith.us/eatit/

    What am I doing wrong to get this working?

    Reply
    • malihu
      Posted on February 3, 2019 at 20:27 Permalink

      Hi,

      Try changing the selector line in the custom script from:

      selector:"._mPS2id-h",

      to:

      selector:".menu-item ._mPS2id-h",

      You could also do this in plugin settings by setting the “Highlight selector(s)” option value to:

      .menu-item a

      Reply
  25. Dambar
    Posted on January 6, 2019 at 06:10 Permalink

    Hi mate

    Scrolling is too fast on mousewheel. It skips the next section if I change scrollSpeed: 400. Is there any options to make it goes to next section not after the next section?

    cheers

    Reply
  26. Balázs Hornyák
    Posted on December 23, 2018 at 23:13 Permalink

    Hi Malihu!

    Everything works fine, except the bullet indicators. I don’t know where I went wrong but I’m using wordpress. And I also don’t know where should I write the: “._mPS2id-h” and wheres these selectors.

    Can I get some help about it?

    Regards!

    Reply
  27. Enrico
    Posted on November 30, 2018 at 12:22 Permalink

    I’m tring to use your plugin on this page https://www.ecopubblicita.it/prova/
    i ‘ve some problem could you help me?
    What’ wrong?
    Thanks
    E

    Reply
    • malihu
      Posted on November 30, 2018 at 19:16 Permalink

      Hi,

      The script should be placed after Page scroll to id plugin files and function call.

      A good place to insert the custom script is in your theme/child theme footer.php template inside a script (<script>...</script>) tag after wp_footer(); function.

      Reply
  28. Yo26
    Posted on October 3, 2018 at 18:29 Permalink

    Hi malihu,

    I am trying to have this scroll directly to sections in my divi one page using your script and the Page scroll to id plugin but I can’t make it work. Could you have a look and let me know if you have an idea why?

    https://goo.gl/rz9tze

    Thanks a lot!

    Reply

Comments pages: 1 2

Post a comment

Cancel reply

Your e-mail is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
You can write or copy/paste code directly in your comment using the <code> tag:
<code>code here...</code>
You may also use the data-lang attribute to determine the code language like so:
<code data-lang-html>, <code data-lang-css>, <code data-lang-js> and <code data-lang-php>

css.php