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

Page scroll to id

Page scroll to id is an easy-to-use jQuery plugin that enables animated page scrolling to specific id within the document. The plugin replaces the default browser behaviour of “jumping” to page sections when links with href value containing hash (#) are clicked, by smoothly animating the page to those sections. You can use it for simple back-to-top links or complex, single-page website navigation and features include: adjustable animation speed, advanced animation easings, vertical and/or horizontal scrolling, ready-to-use classes for links highlighting etc.

Current version 1.5.4 (Changelog)

How to use it

The plugin works simply by connecting links in the form of <a href="#id">link</a>, to sections within the document, in the form of <div id="id">target</div>. Clicking the links will smoothly animate the page to the connected sections.

Get started by Downloading the archive which contains all plugin files and examples. Extract and upload jquery.malihu.PageScroll2id.min.js to your web server.

Include jQuery library (if your project doesn’t use it already) and jquery.malihu.PageScroll2id.min.js in your document’s head tag or at the very bottom of your html, just before the closing body tag (recommended for better performance)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.malihu.PageScroll2id.min.js"></script>

After files inclusion, call mPageScroll2id function on the matching set of elements (selectors) you want the plugin to handle

<script>
    (function($){
        $(window).load(function(){
            $("a[rel='m_PageScroll2id']").mPageScroll2id();
        });
    })(jQuery);
</script>

Using the a[rel='m_PageScroll2id'] selector above, means that the plugin will apply on links with m_PageScroll2id rel attribute value (e.g. <a href="#id" rel="m_PageScroll2id">link</a>). You can change the selector to anything you want (id, class name, js variable etc. – strings that represent ways of choosing elements in the DOM). For multiple selectors, use comma separated values: e.g. a[rel='m_PageScroll2id'], a.class-name, li.menu-item a[href*='#'].

Your links href value should contain # with the id of the section you want to scroll-to and your document should contain sections with such id.

more info

The code is wrapped in (function($){ ... })(jQuery);. This ensures no conflict between jQuery and other libraries using $ shortcut (see Avoiding Conflicts with Other Libraries for more info).

Plugin function is called on window load ($(window).load()) so it executes after all page elements are fully loaded, ensuring the script calculates correctly your content’s length.


By default, the plugin scrolls the page vertically. If your page layout is horizontal (demo), set the layout option parameter to horizontal

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

To enable both vertical and horizontal scrolling (demo), set layout to auto

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

Page scroll to id provides a ready-to-use class for the highlighted links (links whose target element is considered to be within the viewport). The default highlight class is mPS2id-highlight, which you can use in your CSS to style your highlighted links (more info). For example:

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

This sums up the basics of implementing Page scroll to id in your project. For help and detailed usage guides see Code examples & short tutorials and FAQ.

Page scroll to id for WordPress

Automatic installation

Click “Add New” under “Plugins” menu in WordPress administration. Enter “Page scroll to id” into the search field and perform the search. Results should show the plugin. Clicking on “Install Now” will automatically download and install the plugin. When installation is finished, click “Activate Plugin”.

Manual installation

Download the plugin from WordPress plugins repository. Extract files and upload the entire page-scroll-to-id folder to “/wp-content/plugins/” directory on your server. The plugin should now appear in “Plugins” menu in WordPress administration. Click “Activate” under plugin name.

Configure plugin options by clicking “Settings” or through the “Settings › Page Scroll to id” menu.

Page scroll to id for WordPress tutorial
Support forum
FAQ

Configuration

Page scroll to id option parameters
Usage $(selector).mPageScroll2id({ option: value });

scrollSpeed: integer
Sets the scroll animation speed in milliseconds (default: 1300).
Example:
$(selector).mPageScroll2id({ scrollSpeed: 900 });
autoScrollSpeed: boolean
Auto-adjusts animation speed according to target element position and window scroll (default: true).
Example:
$(selector).mPageScroll2id({ autoScrollSpeed: true });
scrollEasing: "string"
Sets the animation easing type when page is idle (easings).
Example:
$(selector).mPageScroll2id({ scrollEasing: "easeInOutExpo" });
scrollingEasing: "string"
Sets the animation easing type while page is animating (easings).
Example:
$(selector).mPageScroll2id({ scrollingEasing: "easeInOutCirc" });
pageEndSmoothScroll: boolean
Adjusts automatically the scroll-to position so when scrolling to a target element that sits at the bottom of the document, the animation stops smoothly at bottom of the page, instead of breaking at an earlier point (default: true).
Example:
$(selector).mPageScroll2id({ pageEndSmoothScroll: true });
layout: "string"
Defines the page scrolling axis.
Value can be "vertical", "horizontal" or "auto".
Example:
$(selector).mPageScroll2id({ layout: "vertical" });
offset: integer, "string", object, function
Defines the amount of pixels to offset the scroll-to position.
The value can a be a positive/negative number, an element selector as string, a js/jquery object, a function or an array.
Code examples
highlightSelector: "string"
The matching set of elements already handled by the plugin that will be highlighted (by default, all selectors are eligible for highlighting).
Code examples
clickedClass: "string"
Sets the class name for the link that’s been clicked (default: mPS2id-clicked)
targetClass: "string"
Sets the class name for the (current) target element (default: mPS2id-target).
highlightClass: "string"
Sets the class name for the (current) highlighted link (default: mPS2id-highlight).
Code examples
forceSingleHighlight: boolean
Allows only one highlighted element at a time (default: false).
Example:
$(selector).mPageScroll2id({ forceSingleHighlight: true });
keepHighlightUntilNext: boolean
Keeps element highlighted until next so at least one element always stays highlighted (default: false)).
Example:
$(selector).mPageScroll2id({ keepHighlightUntilNext: true });
highlightByNextTarget: boolean
Highlight elements according to their target and next target position (default: false).
Useful when targets have zero dimensions.
Example:
$(selector).mPageScroll2id({ highlightByNextTarget: true });
disablePluginBelow: boolean
Disables plugin below [width,height] screen size: boolean, integer, array ([width,height]).
clickEvents: boolean
Enable/disable click events for all selectors (default: true).
Example:
$(selector).mPageScroll2id({ clickEvents: false });
onStart:function(){}
User defined callback function, triggered when scrolling animation begins.
Code examples
onComplete:function(){}
User defined callback function, triggered when scrolling animation is completed.
Code examples

Plugin methods

scrollTo

Usage $.mPageScroll2id("scrollTo","#id");

Calling plugin’s scrollTo method will automatically scroll the page to the id specified in the second parameter.

Method option parameters

layout: "string"
Defines the page scrolling axis.
Example:
$.mPageScroll2id("scrollTo","#id",{
    layout:"auto"
});
offset: integer
Defines the amount of pixels to offset the scroll-to position.
Example:
$.mPageScroll2id("scrollTo","#id",{
    offset:100
});
clicked: boolean
The jQuery object to simulate the click event.
Example:
$.mPageScroll2id("scrollTo","#id",{
    clicked:$(this)
});

destroy

Usage $.mPageScroll2id("destroy");

Calling plugin’s destroy method will completely remove Page scroll to id functionality from all links and targets, returning them to their original state. The method removes all plugin-specific classes, data objects and namespaced events.

Plugin dependencies & requirements

  • jQuery version 1.6.0 or higher
  • Page scroll to id for WordPress

License

This work is released under the MIT License.
You are free to use, study, improve and modify it wherever and however you like.
http://opensource.org/licenses/MIT

Pages: 1 2 3 4


399 Comments

Post a comment

Comments pages: 1 3 4 5

  1. Ryan
    Posted on June 16, 2016 at 23:47 Permalink

    I’m using the plugin to scroll through posts on a single page with the links going to #post-id. I have the post titles in the left column of the page and all of the posts in the right column.
    It works when you first click a post title (not accurately), but once you click one link none of the others work.

    I’m also using it in my nav bar to scroll to a homepage section and that works perfectly so I must be doing something wrong…?

    Reply
    • malihu
      Posted on June 17, 2016 at 00:11 Permalink

      It’s not really possible to help unless I see your page/code. Can you send me your link?

      Reply
  2. Michal
    Posted on June 9, 2016 at 16:48 Permalink

    Fantastic plugin, thank you for devoting your time to building it! Just a quick question – by default the plugin detects change of section and updates link in navigation when the section hits the middle of the viewport. Is there any way of changing it to the bottom of the viewport so that links get updated as soon as a section enters the viewport?

    Thanks

    Reply
    • malihu
      Posted on June 10, 2016 at 16:21 Permalink

      Hello,

      Not sure if you’re using plugin’s WordPress version or not(?)
      You could use plugin’s target_ parameters to manually set the highlight position of each target element – more info.

      For example, you could create a js function that calculates the position and length of each target and set the target_ parameter dynamically. This of course depends on how your sections are set but the following function should normally work.

      Non-WordPress example

      (function($){ $(window).load(function(){ $("a[rel='m_PageScroll2id']").mPageScroll2id(); // Page Scroll to id fn call _setHighlight(); // set custom highlight positions on page load }).resize(function(){ _setHighlight(); // set custom highlight positions on browser resize }); // custom highlight positions function function _setHighlight(){ $("._mPS2id-t").each(function(i){ var $this=$(this), wh=$(window).height(), targetTop=$this.offset().top; $(document).data("mPS2id")["target_"+(i+1)]={ from:-(targetTop-wh), to:-(targetTop+$this.outerHeight()-wh-1) }; }); } })(jQuery);

      WordPress plugin

      If you’re using the WordPress plugin, you should add the following js script in your theme’s footer.php after wp_footer() function:

      <script> (function($){ $(window).load(function(){ _setHighlight(); // set custom highlight positions on page load }).resize(function(){ _setHighlight(); // set custom highlight positions on browser resize }); // custom highlight positions function function _setHighlight(){ $("._mPS2id-t").each(function(i){ var $this=$(this), wh=$(window).height(), targetTop=$this.offset().top; $(document).data("mPS2id")["target_"+(i+1)]={ from:-(targetTop-wh), to:-(targetTop+$this.outerHeight()-wh-1) }; }); } })(jQuery); </script>

      Notes and plugin’s highlighting logic

      I’m not sure why you want to start highlighting the links/sections the moment they enter the bottom of the viewport(?) The plugin is set to use a visual logic, meaning that highlight occurs when the section is within user’s actual visual field (approx. at the middle of the viewport).

      For instance, it’s normal that when a user reads the bottom of section 1, he has already scrolled past the point of where section 2 appears on the screen. This of course depends on your layout but in general, when a user starts viewing/reading a section, this section’s top is at (or has passed) the vertical center of the screen.

      Reply
      • Michal
        Posted on June 10, 2016 at 21:48 Permalink

        Thank you for the extensive reply, I will try your script out. Apologies I should have mentioned I am using the jQuery version. The reason for my request is that I have a navigation in the top left corner which I would like to change colour depending on the background of each section. If section 1 is light and section 2 is dark, the navigation changes to light half way through the screen. So the fixed navigation at the top of the screen becomes light when in fact it still is on a light and not dark background since we can still see the lower half of section 1..

        Reply
        • malihu
          Posted on June 11, 2016 at 15:07 Permalink

          I see. Let me know if the above helps.

          Reply
  3. gretchen
    Posted on May 28, 2016 at 00:19 Permalink

    I am having trouble with the position:fixed navbar on mobile with a horizontal scrolling site. i came back to see how you handled it, and see that you have the same issueโ€”the nav slides off to the left as you scroll. Any ideas on how to fix? I’ve tried backface-visibility and translateZ suggestions from other sites.

    Reply
    • malihu
      Posted on May 29, 2016 at 23:30 Permalink

      I can’t see the navigation menu scrolling with the page on the demos… The fixed element stays fixed (as it should). I’ve checked it on iPad, Windows Phone etc. Does it happen on a particular device/OS/browser?

      Reply
  4. Leo
    Posted on May 19, 2016 at 23:29 Permalink

    how can i use scrollTo function on wordpress plugin ?

    i want to the page scroll like fullscreen scroll or one page scroll

    like this one http://www.thepetedesign.com/demos/onepage_scroll_demo.html

    Reply
    • malihu
      Posted on May 29, 2016 at 23:43 Permalink

      The scrollTo function can be used within your own scripts and functions (or within scripts by the theme and other plugins). There’s no difference in using the method within WordPress or not. If you have the plugin activated, scrollTo method will work.

      To replicate the layout and functionality on the link you posted, you have to create the one page template along with the javascript functions that’ll hold the events for keyboard arrows and bullet indicators. Within those events you could use the scrollTo method.

      There’s no automatic way of doing all these unless you use a WordPress theme that includes such template.

      Reply
  5. Chris Anderson
    Posted on May 16, 2016 at 18:18 Permalink

    HI.

    Quick question: Just wondering if you can set the pages to auto scroll rather then onclick?

    Reply
    • malihu
      Posted on May 16, 2016 at 19:27 Permalink

      Hi,

      Not sure what you mean by “auto scroll”(?) What would be the triggering action to scroll the page to an id? Can you describe a functionality or a situation you have in mind?

      Perhaps the scrollTo method is what you need but I can’t say for sure.

      Reply
      • chris
        Posted on May 17, 2016 at 17:07 Permalink

        Basically I just mean like a Slideshow. I really like this idea but I guess my situation is a bit different. I will need complex pages of dynamic content which this can handle, but it will be displayed publicly and will scroll automatically. It’s basically going to be like a community events/calendar board.

        Does that make sense?

        Reply
        • malihu
          Posted on May 17, 2016 at 18:30 Permalink

          You can use plugin’s scrollTo method in your own function(s) to trigger a page scroll:
          $.mPageScroll2id("scrollTo","#some-id");

          The only limitation is that the plugin works only on documents root element (html/body). It cannot scroll an overflowed div which is what a typical slider does.

          If you plan to auto-scroll the whole page, then you can easily use the method above in your script(s).

          Reply
          • chris
            Posted on May 17, 2016 at 22:40 Permalink

            Ok great, probably just what I’m looking for. Thanks again for the help. I’ll bug you again if I run into any issues.

            Cheers,
            Chris

        • malihu
          Posted on May 17, 2016 at 23:15 Permalink

          No problem. If you need help let me know.

          Reply
  6. anna esc
    Posted on May 12, 2016 at 20:15 Permalink

    Hi. I would like to know how can I highlight the menu-item “Recetas y consejas” in my webstite (it’s the blog) when I am in a single post. I have tried this and didn’t work:
    .single-post #headerwrap li.menu-item-4583 > a{ color: #00e6b4; }
    Thank you.
    website: http://www.greenstinct.com

    Reply
    • malihu
      Posted on May 13, 2016 at 12:20 Permalink

      I think you should try:
      .single-post #headerwrap #menu-item-4583 > a{ color: #00e6b4; }

      Reply
  7. Mirko
    Posted on April 20, 2016 at 19:57 Permalink

    Hi Manos,

    Just one quick question. Is there a way to delay the start of scrolling?

    This could be useful for mobile devices, especially if there is an fullscreen overlay navigation involved ๐Ÿ™‚

    Example: User clicks on the navigation item, navigation is first animated out, and then the scrolling to specific section starts.

    Basically what I want is delay option, in my case it would be the same length as the overlay navigation fade-out animation.

    Reply
    • malihu
      Posted on April 21, 2016 at 04:18 Permalink

      Hi,

      Do you use the plugin within WordPress? Also, do you want this delay when navigating from/to different pages/URL?

      If both of the above apply, you can set a delay for “Scroll to location hash” in plugin settings.

      Reply
      • Mirko
        Posted on April 28, 2016 at 21:51 Permalink

        Hi Manos,

        Sorry for the late reply !

        No, I am using the jQuery version. I just need the delay option that I can use on smaller screens, so that I can finish hiding the overlay navigation and then executing the scroll to desired element.

        Hope ypu get me ๐Ÿ™‚

        Reply
        • malihu
          Posted on April 29, 2016 at 13:59 Permalink

          Sure.

          There’s no delay option but you can do it manually.

          You need to disable the click event via the clickEvents option parameter and use plugin’s scrollTo method inside your custom click event with the delay you want.

          I’m posting a working code example which should do what you need:

          (function($){ var ps2idSelector=$("a[rel='m_PageScroll2id']"), //set your element selector ps2idDelay, ps2idTimeout; $(window).load(function(){ ps2idSelector.mPageScroll2id({ clickEvents:false //disable click event }); ps2idSelector.click(function(e){ //add custom click event which calls scrollTo method e.preventDefault(); var $this=$(this); if(ps2idTimeout){clearTimeout(ps2idTimeout);} ps2idTimeout=setTimeout(function(){ //scrollTo method $.mPageScroll2id("scrollTo",$this.attr("href"),{ clicked:$this }); },ps2idDelay); }); }).on("load resize",function(){ //set/change delay accordingly var winSize=$(this).width(); if(winSize<=1024){ ps2idDelay=600; //delay in milliseconds }else{ ps2idDelay=0; } }); })(jQuery);

          Reply
          • Mirko
            Posted on May 4, 2016 at 00:47 Permalink

            Thanks Manos!! Working like a charm ๐Ÿ™‚

  8. Brian
    Posted on April 15, 2016 at 20:01 Permalink

    Hello Manos,

    Very nice work on this plugin. I appreciate that you have created it so thoroughly. I was hoping you could help me with one issue I’m having:

    I have the “Enable on WordPress Menu links” option selected and I can’t seem to get the offset to work. I enter a value of 50 as the offset but it does not do anything.

    The page is successfully scrolling to the id but I need it to be offset by 50 pixels or so in order to give me room off of the fixed header.

    The site URL is currently at http://kalamazoocraftsman.com/v2

    Any ideas?

    Thank you,

    Brian

    Reply
    • malihu
      Posted on April 15, 2016 at 20:59 Permalink

      Hello Brian,

      I checked your link and it seems that your menu links are not handled by ‘Page scroll to id’.

      I inspected the links via browser’s dev tools and they have an additional js click event which seems to scroll the page and prevent ‘Page scroll to id’ page scrolling. This is why offset is not working (it’s not calculated because plugin’s click event is overwritten).

      The additional click event is probably coming from a script within your theme or some other plugin(?)
      Maybe there’s a setting to disable it and let ‘Page scroll to id’ handle page scrolling?

      I also created a test link outside the menu (via dev tools) and page scrolling as well as offset worked as expected, which confirms that another script is handling your menu links.

      Reply
  9. choco
    Posted on April 13, 2016 at 01:27 Permalink

    Does this works without user clicking on the section?
    I want it to remember the place it is on reload, will it work for that?

    Reply
    • malihu
      Posted on April 14, 2016 at 00:58 Permalink

      Yes although I’m not sure what you mean.
      Page refreshing will work the same with or without the plugin. For example on the demo, if you scroll down (or click on any link) and then refresh the page, the scroll position will be where it was before (it’s browser’s feature).

      Reply
  10. Benji
    Posted on March 24, 2016 at 19:27 Permalink

    Hello!

    Love your plugin โ€” I’ ve just used it with a site that has a fixed header, however upon scrolling the header jerks up and down. Any ideas? Thanks!

    Reply
    • malihu
      Posted on April 4, 2016 at 17:25 Permalink

      Hello,

      Not sure if you still have this issue but normally, the “jerking” you describe should not be related with ‘Page scroll to id’. Does the header jerking happen when you scroll the page via mousewheel? It sounds more like an issue with the fixed header itself(?)
      Can you send me your link?

      Reply

Comments pages: 1 3 4 5

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