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

Page scroll to id

Code examples & short tutorials

Using offsets

You can offset the scroll-to position via the offset option parameter and/or via the data-ps2id-offset html attribute.

offset option parameter provides a general offset for all the links handled by the plugin. For example, setting offset value to 50 will stop page scrolling 50 pixels before reaching the target

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:50
});
data-ps2id-offset attribute provides link specific offsets. The data attribute overwrites the offset option and is useful when you need to set a different offset for a link

<a href="#id" rel="m_PageScroll2id" data-ps2id-offset="100">link</a>

When the link above is clicked, it will stop page scrolling 100 pixels before reaching the target.

The offset value can be a positive or negative number, a string representing an element selector, a js or jquery object, a function or an array of values.

Integer

Offsets scroll-to position by x amount of pixels (positive or negative number). Examples:

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:50
});
<a href="#id" rel="m_PageScroll2id" data-ps2id-offset="100">link</a>
$.mPageScroll2id("scrollTo","#id",{
    offset:-50
});

String

Offsets scroll-to position by element height/width/position. Examples:

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:"#id"
});
<a href="#id" rel="m_PageScroll2id" data-ps2id-offset=".class-name">link</a>

js/jquery object

Offsets scroll-to position by element height/width/position. Examples:

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:document.getElementById("id")
});
$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:$("#id")
});

Function

Offsets scroll-to position via function. Examples:

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:function(){
        return offsetFn();
    }
});

function offsetFn(){
    var myOffsetY=50,
      myOffsetX=100;
    return [myOffsetY,myOffsetX];
}

Array

Offsets vertical (y) and horizontal (x) scroll-to positions separately. Examples:

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:{"y":"50","x":"100"}
});
<a href="#id" rel="m_PageScroll2id" data-ps2id-offset='{"y":"#id","x":"0"}'>link</a>
$("a[rel='m_PageScroll2id']").mPageScroll2id({
    offset:{"y":document.getElementsByTagName("nav") || "ul.nav","x":"0"}
});

User defined callbacks

You can trigger your own js function(s) by calling them inside onStart and onComplete option parameters. For example:

$("a[rel='m_PageScroll2id']").mPageScroll2id({
    onStart:function(){
        myCustomFn1();
    },
    onComplete:function(){
        myCustomFn2();
    }
});

function myCustomFn1(){
    console.log(mPS2id.target.attr("id"));
}
function myCustomFn2(){
    console.log(mPS2id.scrollTo.y);
}

Returning values

The script returns the following values and objects

  • mPS2id.trigger – the event which triggered page scrolling. Returned values: “selector” (click), “scrollTo” (method)
  • mPS2id.clicked – the element that was clicked as jQuery object
  • mPS2id.target – the target element as jQuery object
  • mPS2id.scrollTo.y – the vertical scroll-to position (pixels)
  • mPS2id.scrollTo.x – the horizontal scroll-to position (pixels)

Using Page scroll to id with deep linking plugins

There are many solutions for deep linking via javascript. The archive contains examples of using Page scroll to id with jquery.address and jquery-hashchange.

Normally, you’ll use plugin’s scrollTo method to trigger page scroll in hash-change events. If you need to disable the click events of selectors, set clickEvents to false

$("a[rel='m_PageScroll2id']").mPageScroll2id({
  clickEvents:false
});

$(window).hashchange(function(){
  var loc=window.location,
    to=loc.hash.split("/")[1] || "#top";
  $.mPageScroll2id("scrollTo",to,{
    clicked:$("a[href='"+loc+"'],a[href='"+loc.hash+"']")
  });
});

Dynamic content

When adding links and/or sections to your page dynamically (e.g. via ajax, js click events etc.) you may need to re-call mPageScroll2id function after your new content is fully loaded: $.mPageScroll2id(); This ensures the script will highlight your newly added links and targets correctly. If you don’t use plugin’s highlight feature, you can skip mPageScroll2id function call.

The plugin highlights links automatically. When the page is scrolled (by clicking a link, mouse-wheel, touch-swipe etc.), the script checks if a target element is within the viewport and adds a highlight class (default: mPS2id-highlight) to the corresponding link(s).

You can change the default highlight class to your own, through the highlightClass option parameter

$("a[rel='m_PageScroll2id']").mPageScroll2id({
  highlightClass:"highlighted-menu-item"
});

By default, all links handled by the plugin are eligible for highlighting. Normally, you’d want to highlight only certain links such as those in navigation menus and not others like back-to-top. This can be achieved either by styling only the CSS selector you want, for example:

.menu a.mPS2id-highlight{ 
    background: #ff0; 
}

or by inserting the selectors subset in the highlightSelector option parameter

$("a[rel='m_PageScroll2id']").mPageScroll2id({
  highlightSelector:".menu a"
});

The plugin also provides a way of manually setting the highlight positions of each target element. If you need to set a specific area (in pixels) at which the highlight class is added, use the option parameter target_ followed by the number of your target within your document

$("a[rel='m_PageScroll2id']").mPageScroll2id({
  target_1:{ from:0, to:-799 },
  target_2:{ from:-800, to:-1599 },
  target_3:{ from:-1600, to:-2399 }
});

The target_ option gets the values { from, to, fromX, toX }

When multiple targets are within the viewport, more than one links will be highlighted simultaneously. If you don’t want this behavior, set forceSingleHighlight option parameter to true

$("a[rel='m_PageScroll2id']").mPageScroll2id({
  forceSingleHighlight:true
});

Alternatively, you can target the first and last highlighted elements by using the classes .mPS2id-highlight-first and .mPS2id-highlight-last.


Plugin home     Project on GitHub

Pages: 1 2 3 4


487 Comments

Post a comment

Comments pages: 1 4 5 6

  1. Paul
    Posted on August 10, 2017 at 17:36 Permalink

    Hello,

    I’m running into an issue with every anchor link smooth scroll plugin I try to install. The anchor links jump to the page section, but won’t scroll. There could be a conflict with another plugin, but am not sure. Also could be a theme issue—using an older “Gantry” theme.

    Under “advanced options”, the “Prevent other scripts from handling plugin’s links (if possible)” box has been checked. No luck with that though.

    To see an example, you can navigate to this page and click the HSS logo link (under “strategy”), which should send you to another page and scroll down to the “strategy” paragraph, but currently jumps to the section. At the moment, this is the only “page scroll to id” link I have set up.

    Any insight and/or troubleshooting ideas would be appreciated.

    Reply
    • Paul
      Posted on August 10, 2017 at 18:18 Permalink

      Also, when I try adding a css selector such as “a.consulting-nav[href*=’#’]”, the anchor link functionality stops working completely.

      Reply
      • Paul
        Posted on August 10, 2017 at 18:27 Permalink

        Aha! 10 pages into the support forum and I found the solution! Was a conflict with the “jQuery updater” plugin. After deactivating, the scroll functionality works.

        Reply
        • Paul
          Posted on August 10, 2017 at 18:46 Permalink

          Ahh… spoke too soon. After disabling the “jQuery updater” plugin, the anchor links that load another page work, but the one’s that should scroll within the same page do not.

          Example: “contact” button (underneath logo) on this page.

          Reply
          • Paul
            Posted on August 10, 2017 at 22:10 Permalink

            If this helps, after clicking the link, the console gives the following error:

            page-scroll-to-id.min.js?ver=1.6.2:2 Uncaught TypeError: a[s].match is not a function
            at HTMLAnchorElement. (page-scroll-to-id.min.js?ver=1.6.2:2)
            at Function.each (jquery.js?ver=1.12.4:2)
            at a.fn.init.each (jquery.js?ver=1.12.4:2)
            at _scrollSpeed (page-scroll-to-id.min.js?ver=1.6.2:2)
            at _scrollTo (page-scroll-to-id.min.js?ver=1.6.2:2)
            at HTMLAnchorElement. (page-scroll-to-id.min.js?ver=1.6.2:2)
            at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3)
            at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)

    • Paul
      Posted on August 11, 2017 at 17:31 Permalink

      UPDATE:

      I’ve resolved the issue. Downloaded the developer version of the plugin (https://downloads.wordpress.org/plugin/page-scroll-to-id.zip). Ran into a speed bump trying to upload via the WordPress dashboard. Had to unzip and upload the folder through FTP. Once activated, the newer version of the plugin worked across appropriate links!

      Reply
      • malihu
        Posted on August 15, 2017 at 18:31 Permalink

        Sorry for the late reply (seems I missed your comment). Yes, using the developer version fixes this error. Thanks for posting the solution.

        Reply
  2. John Merlo
    Posted on August 3, 2017 at 01:29 Permalink

    This is at the top of page
    [ps2id id=’some-id’ target=”/]

    this is at bottom when at bottom I want to go to top does not work?
    Back to Top

    Reply
  3. Mr Strangerous
    Posted on July 29, 2017 at 01:58 Permalink

    I’m unsure how to fix this issue, but the plugin works AMAZINGLY – no complaints : There is simply just a rather annoying interference with the theme I currently have – that I also absolutely love (SYDNEY) on WordPress.
    The problem is as follows: The scroll to ID works flawlessly – though instead of stopping so the sticky menu doesn’t overlap it – it simply gets hidden behind. How can I implement a way to make the scroll stop at the MENU rather than the top of the page? Besides this I think this is an absolutely flawless plugin! Great work.

    I’ve tried creating rows above my titles (just for the p2id scroller to stop at, though this has been unsuccesful)

    Reply
  4. Sarah C
    Posted on July 26, 2017 at 03:41 Permalink

    Hi!

    Great plug-in. Thank you.
    You might have answered this question already (cnfr. Scrolling smoothly from/to different pages etc.) but I do not know how to change the Scroll Speed or how to make it Scroll smoothly.
    I’m not on wordpress.

    Could you help me with this?
    Thank you so much,
    Best,
    Sarah

    Reply
    • malihu
      Posted on July 26, 2017 at 19:11 Permalink

      Hello Sarah,

      To have this functionality in the non-WordPress plugin, you need to add extra js/jquery code:

      (function($){ var _hash=location.hash || null, _validateLocHash=function(val){ try{ var $val=$(val); }catch(error){ return false; } //avoid js errors on invalid selectors return $(val).length && $("a[href*='"+val+"']").length; }; $(document).ready(function(){ if(_hash){ if(_validateLocHash(_hash)){ var href=window.location.href.replace(/#.*$/,"#"); $(window).scrollTop(0); //stop jump to hash straight away if(window.history && window.history.replaceState){ window.history.replaceState("","",href); }else{ window.location.href=href; } } } }); $(window).on("load",function(){ $("a[rel='m_PageScroll2id']").mPageScroll2id(); //Page Scroll to id fn call if(_hash){ if(_validateLocHash(_hash)){ $(window).scrollTop(0); //jump/start from the top setTimeout(function(){ $.mPageScroll2id("scrollTo",_hash); //scroll to location hash on page load if(window.history && window.history.replaceState){ window.history.replaceState("","",_hash); }else{ window.location.hash=_hash; } },0); //optional delay } } }); })(jQuery);

      Let me know

      Reply
      • Sarah C
        Posted on July 27, 2017 at 17:15 Permalink

        Hi,

        Thank you for your response.
        So do I have to paste it after this? (see code bellow)

        I’m really new to js so any info would be really helpful. Also, how would I control the speed?

        Thank you so much,
        Best,
        S

        /* plugin constructor functions */

        $.fn[pluginNS]=function(method){
        if(methods[method]){
        return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
        }else if(typeof method==="object" || !method){
        return methods.init.apply(this,arguments);
        }else{
        $.error("Method "+method+" does not exist");
        }
        };
        $[pluginNS]=function(method){
        if(methods[method]){
        return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
        }else if(typeof method==="object" || !method){
        return methods.init.apply(this,arguments);
        }else{
        $.error("Method "+method+" does not exist");
        }
        };

        /*
        allow setting plugin default options.
        example: $.plugin_name.defaults.option_name="option_value";
        */

        $[pluginNS].defaults=defaults;

        })(jQuery,window,document);

        Reply
        • malihu
          Posted on July 28, 2017 at 04:50 Permalink

          No, you don’t need to edit jquery.malihu.PageScroll2id.js. Leave as it is so you can upgrade to a new plugin version easily if/when you need to.

          You simply replace plugin’s function call with the code above.
          For instance, in your HTML:

          <!-- jquery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- plugin script --> <script src="jquery.malihu.PageScroll2id.min.js"></script> <!-- plugin fn call / init --> <script> /* the code I posted goes here... In the code, the actual function call is commented as "Page Scroll to id fn call" (in case you want to modify its options) */ </script>

          Reply
          • sarah
            Posted on July 29, 2017 at 01:32 Permalink

            Thank you!

  5. Jaime
    Posted on May 18, 2017 at 14:24 Permalink

    Hi there!
    Thanks a lot for your plugin, it’s great.

    I’ve one question I’m not able to solve.
    Everything goes ok, but when I clik one page in my main menu, it refresh the page (before going to the target).

    You can have a look here.
    http://senderosdemusicas.com/home-food

    What i’m missing?
    Thanks a lot!
    🙂

    Reply
    • malihu
      Posted on May 18, 2017 at 16:33 Permalink

      Hello,

      This is happening because your web server is set to remove the trailing slash from the URL automatically. So:
      http://senderosdemusicas.com/home-food/
      becomes:
      http://senderosdemusicas.com/home-food

      Notice how the last/trialing slash (/) is missing.
      For the browser, these 2 URL are different, thus the page refreshes.

      This happens simply because you’ve set your links URL to use a trailing slash. If you remove it the problem will be fixed. For example, change “ARTISTAS” link to:
      http://senderosdemusicas.com/home-food#artistas
      i.e. remove the slash before the hash (#) and it’ll work as expected 😉

      Reply
  6. Trktrk
    Posted on May 6, 2017 at 18:21 Permalink

    How do I instal this plugin in WordPress??
    I tried uploading it but i get an error. When uploading via FTP I cannt see it in plugin list in WordPress

    Reply
  7. Krystian Millora
    Posted on May 3, 2017 at 07:11 Permalink

    Hi, Awesome plugin

    but how can I change the color of the nav-item when I click or highlight the specific nav? I’ve used the “a._mPS2id-h.mPS2id-clicked.mPS2id-highlight” but it didn’t work for me. Thank you

    Reply
    • malihu
      Posted on May 4, 2017 at 00:36 Permalink

      Hi,

      Did you fix it? It seems to work for me now.

      Reply
  8. James
    Posted on March 27, 2017 at 18:45 Permalink

    Hi there

    I’ve said it before and I’ll say it again – your plugins are great!

    I have something that is bugging me though and I can’t see what I’m doing wrong. On the above web page there are links in the submenu to another page – the page should scroll to the offset of the ID but it doesn’t. Scrolling works within the page but not between pages. It’s as though the script is not being called.

    Can you help please?

    Thanks

    James

    Reply
    • james
      Posted on March 27, 2017 at 18:47 Permalink

      the weblink didn’t reproduce – here it is again.

      Reply
    • malihu
      Posted on March 28, 2017 at 02:22 Permalink

      Hello,

      Scrolling smoothly from/to different pages is only available on the WordPress plugin. You need to add some extra code in order to get this functionality with the simple jQuery plugin.

      You should edit your jquery.functions.js file and remove $("a[rel='m_PageScroll2id']").mPageScroll2id({ scrollSpeed: 1500, offset: 120 }); (it’ll be moved below) and add the following code at the end of the file (after the last });):

      (function($){ var _hash=location.hash || null, _validateLocHash=function(val){ try{ var $val=$(val); }catch(error){ return false; } //avoid js errors on invalid selectors return $(val).length && $("a[href*='"+val+"']").length; }; $(document).ready(function(){ if(_hash){ if(_validateLocHash(_hash)){ var href=window.location.href.replace(/#.*$/,"#"); $(window).scrollTop(0); //stop jump to hash straight away if(window.history && window.history.replaceState){ window.history.replaceState("","",href); }else{ window.location.href=href; } } } }); $(window).on("load",function(){ $("a[rel='m_PageScroll2id']").mPageScroll2id({ scrollSpeed: 1500, offset: 120 }); //Page Scroll to id fn call if(_hash){ if(_validateLocHash(_hash)){ $(window).scrollTop(0); //jump/start from the top setTimeout(function(){ $.mPageScroll2id("scrollTo",_hash); //scroll to location hash on page load if(window.history && window.history.replaceState){ window.history.replaceState("","",_hash); }else{ window.location.hash=_hash; } },0); //optional delay } } }); })(jQuery);

      Reply
      • James
        Posted on March 28, 2017 at 12:00 Permalink

        That’s perfect – thanks!

        Since sending you the message, I did manage to get a a form of it to work in another version but only to partially.

        I’m very grateful.

        🙂

        Reply
  9. gamatire
    Posted on March 26, 2017 at 11:01 Permalink

    Thanks that was helpful

    Reply
  10. horstmith
    Posted on March 16, 2017 at 19:39 Permalink

    Hey, great plugin!

    but, how can i change the color of the font?
    i tried everything. i use WordPress with the semplice theme.

    here is the button i want to change the color of the font:
    http://maxlorenz.com/?work=63&cs=1

    thanks a lot!

    Reply
    • malihu
      Posted on March 16, 2017 at 20:19 Permalink

      Changing font color is done via CSS as with any kind of link (it doesn’t matter if the link is added or handled by “Page scroll to id”).
      You should edit your theme’s stylesheet (or custom CSS) and set the color you want. For example, to set a color for links handled by the plugin (e.g. your “SKIP” link), you can add:

      a._ps2id { color: #c0c0c0; }

      and for the hover state:

      a._ps2id:hover { color: #000; }

      Reply
  11. Josh
    Posted on March 11, 2017 at 07:05 Permalink

    Just started my own WordPress website for a portfolio and I really love this plug-in. For the twenty seventeen theme it might be helpful to be able to scroll so that the bottom of an element is aligned with the bottom of the browser window (viewport?) rather than the default which is that the top of the element aligns with the top of the window. It looks like someone already commented on this but the solution seemed to only work for elements with fixed heights, or maybe there is already a way to do it but I can’t quite figure it out. Would it be possible to have an option for the target to be at the top or bottom of the viewport?

    Reply
    • Josh
      Posted on March 11, 2017 at 07:34 Permalink

      I’m looking for something like this: https://jsfiddle.net/L56wxhqm/32/

      Reply
    • malihu
      Posted on March 11, 2017 at 21:23 Permalink

      Hi,

      I can’t really say if this functionality can be added as a plugin feature/option on a future version. I’ll need to make extensive tests and if everything goes well, I’ll add it.

      For now, you’ll need to use javascript (for elements with non-fixed height).
      You can add a script (<script>) in your theme’s template (e.g. in footer.php after wp_footer function) that’ll change the offset of a specific link/target dynamically.

      Example:

      <script>

      (function($){ $(window).on("load resize",function(){ var val="#panel2"; //set your element's id/hash fragment value $("a[href*='"+val+"']").data("ps2id-offset",function(){ return $(window).height()-$(val).height(); }); }); })(jQuery);

      </script>

      The above will make your “Tinkerbot” link scroll until the bottom of #panel2 section reaches the bottom of the viewport.

      Reply
      • Josh
        Posted on March 12, 2017 at 03:01 Permalink

        This is awesome!! Thanks so much for your quick response and help. I got it working really well with a click event on the top menu. The way I did it is probably not the most efficient way but it works for this site. Donated. Have a beer on me 🙂

        Reply
        • malihu
          Posted on March 12, 2017 at 07:07 Permalink

          Good call. Looks good to me 😉
          Thanks a lot for your donation and support!

          Reply

Comments pages: 1 4 5 6

Post a comment

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