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

Scroll to id within element with custom scrollbar(s)

A simple jquery function to make all links pointing to id attributes within the page, work on content with custom scrollbars.

Place the following function within a script or external .js to make all links in the form of <a href="#id">Go to #id</a> trigger the scrollTo method of custom scrollbar plugin if necessary

$(document).on("click","a[href^='#']",function(e){
  var href=$(this).attr("href"),target=$(href).parents(".mCustomScrollbar"); 
  if(target.length){
    e.preventDefault();
    target.mCustomScrollbar("scrollTo",href);
  }
});

39 Comments

Post a comment
  1. jay
    Posted on September 19, 2019 at 16:02 Permalink

    Team, I am using this scrollbar in my project to display the all categories in horizontal view.

    Now when I scroll left and choose the end category so page load with that particular category result

    But the page is not redirecting or not showing that selected category on the front after page load. I have to scroll the scrollbar again.

    I tried with scrollto option but it didn’t work.

    Reply
  2. Nur
    Posted on March 5, 2019 at 03:28 Permalink

    Great plugin. Just facing an obstacle with integrating bootstrap scroll spy and mcustomscrollbar. When I enable the mcustomscrollbar bootstrap scroll spy stop working.
    Looking forward to your response.
    Thanks in advance

    Reply
  3. Pradeep
    Posted on January 15, 2019 at 13:24 Permalink

    Hi,

    Plugin is not compatible in IE. Even there is a scroll bar where I don’t have scrolling. Means in each div it is showing scroll bar even though there is scroll or not.
    Any suggestion?

    Reply
  4. Jaradona
    Posted on November 6, 2018 at 18:24 Permalink

    Hi, I’m using the mCustomScrollbar, it is nice..
    I have a problem and after many efforts I wasn’t able to find the solution, I’m working on ASP.net project and I’ve made a master page that has a scrollable div named “MPageContent” (content place holder), everything works fine till now, I’ve used the following code in the master page:

    (function ($) {
    $(window).on(“load”, function () {

    $(“#MPageContent”).mCustomScrollbar({
    setHeight: 515,
    theme: “inset-2-dark”
    });

    });
    })(jQuery);

    the problem appeared when I used a scrollable multiline textbox inside the content page (multiline textbox inherits from textarea), I applied the mCustomScrollbar to the multiline textbox, the mCustomScrollbar works inside the textbox, but everytime the multiline textbox receives focus, the MPageContent (Parent div in the master page) losses its current position and returns to top page (as if there was a postback)… I will really appreciate any help, thanks.

    Reply
  5. Reka
    Posted on October 5, 2018 at 15:44 Permalink

    Dear Malihu

    My name is Reka, I now learn informatica.
    First: I like your site, very intersting the srollbar.
    Unfortunately, I dont can make my code.
    Please help me, if He has time.
    Sorry, but I very bad speak english.


    <div class="control"> <a href="#['top',null]" rel="content-yx" class="backtotop">TOP</a> </div>

    I learn Html and css, I make mCustomScrollbar code, but not work.

    My code is work, if no mCustomScrollbar, but together not work 🙁
    <!-- Back To Top --> <script type="text/javascript"> $(document).ready(function () { $(window).scroll(function () { if ($(this).scrollTop() > 100) { $('.backtotop').fadeIn(); } else { $('.backtotop').fadeOut(); } }); $('.backtotop').click(function () { $("html, body").animate({ scrollTop: 0 }, 800); return false; }); }); </script>

    I verry verry thanks,
    Greetings

    Reka

    Reply
  6. Karthik
    Posted on September 26, 2017 at 12:07 Permalink

    $timeout(function (){ $(".dashboard-menu, .accordion-container, .participants-detail-container, .events-view .events-month, .table-scroll, .table-scroll tbody, .multi-chk-bx").mCustomScrollbar({ axis:"yx", scrollButtons:{enable:true}, advanced:{autoScrollOnFocus:false}, theme:"minimal", scrollbarPosition:"outside" }); $(".page-container, .output-container, .jdash-widget .jdash-body, .dashboard-container, .alert-popup .alert-popup-pane, .player-listings, .sidebar, .msg-container ul, .msg-log .msg-history, .pgm-listings").mCustomScrollbar({ axis:"y", scrollButtons:{enable:true}, advanced:{autoScrollOnFocus:false}, theme:"minimal", scrollbarPosition:"outside" }); $('#msg-history').mCustomScrollbar('scrollTo', 'last'); });
    In my above code, #msg-history only scrollto Last action…. But all of my scrollable element also scrollto Last… Any idea…

    Reply
  7. mayur
    Posted on April 29, 2017 at 07:30 Permalink

    hey..
    i’m using your costume scrolling plugins my site scrolling too slow plz tell me how to increase scrolling speed using this costume scrollbar?

    Reply
  8. siva
    Posted on October 3, 2016 at 14:15 Permalink

    Yes it is really working and thanks

    Reply
  9. Chirag
    Posted on June 21, 2016 at 18:41 Permalink

    Here I need help to achieve scrolling to specific element,
    which I can get by the code given below, But this is scrolling with animation.

    Is there any way to remove scrolling animation while I scroll to specific element.

    Thanks!

    Reply
    • malihu
      Posted on June 24, 2016 at 00:53 Permalink

      Sure. Set the scrollInertia option of scrollTo method to 0. For instance, in the article’s code change:

      target.mCustomScrollbar("scrollTo",href);

      to:

      target.mCustomScrollbar("scrollTo",href,{scrollInertia:0});

      Reply
  10. Prajwol dangol
    Posted on March 30, 2016 at 11:18 Permalink

    Thanks man. This article saved my life !! Finally able to scroll to the targeted element inside the scrollbar enabled section.

    I am just confused about one thing, why JQuery method to scroll to element not working? Is there some reason behind this ?

    Reply
  11. Alo
    Posted on March 22, 2016 at 13:20 Permalink

    Hello,

    I came to your site here from the WordPress support site (Page scroll to id), where someone asked about mouse scroll to id. So far it seems like what I found on your site here seems to be it? Could you give me a few pointers on how to implement it in WP? I’m sorry but this is the first time implementing jquery plugins, so sorry if I seem a bit daft 🙂

    Reply
    • Alo
      Posted on March 22, 2016 at 13:26 Permalink

      A better example would probably be another “Page scroll to id” support post (https://wordpress.org/support/topic/full-page-scrolling-with-mousewheel) I saw, in which you describe a bit how to implement it into WP. Right now I have set all my sections to be 100% height with this code:

      jQuery(function($){ var windowH = $(window).height(); var wrapperH = $('#my-section').height(); if(windowH > wrapperH) { $('#my-section').css({'height':($(window).height()-71)+'px'}); } $(window).resize(function(){ var windowH = $(window).height(); var wrapperH = $('#my-section').height(); var differenceH = windowH - wrapperH; var newH = wrapperH + differenceH; var truecontentH = $('#my-section .x-container').height(); if(windowH > truecontentH) { $('#my-section').css('height', (newH-71)+'px'); } }) });

      But now I would like to set mouse scrolling to also scroll one whole section at a time. Until now I’ve been pretty much flabbergasted..

      Any help would be greatly appreciated!

      Reply
  12. Mattieu
    Posted on January 16, 2016 at 21:23 Permalink

    Hello,

    Is it possible to combine jQuery custom content scroller & Page scroll to id ?

    I’m using jQuery custom content scroller and the above code to scroll to my divs :
    $(document).on(“click”,”a[href^=’#’]”,function(e){
    var href=$(this).attr(“href”),target=$(href).parents(“.mCustomScrollbar”);
    if(target.length){
    e.preventDefault();
    target.mCustomScrollbar(“scrollTo”,href);
    }
    });

    but I would like to highlight my menu links when the div appears. I tried using Page scroll to id by it doesn’t work. Can you please tell me if it’s possible, and if it is, can you provide an example ?

    thanks !

    Reply
    • malihu
      Posted on January 16, 2016 at 21:52 Permalink

      You cannot use the two scripts on the same element as ‘Page scroll to id’ requires browser’s native/default scrollbar.

      What you can do is use plugin’s jQuery expressions (see “Plugin-specific jQuery expressions” section at the end of plugin post) to do something like:

      $(selector).mCustomScrollbar({ callbacks:{ whileScrolling:function(){ if($("#some-id").is(":mcsInView")){ $("a[href='#some-id']").addClass("highlight-class"); }else{ $("a[href='#some-id']").removeClass("highlight-class"); } } } });

      Hope this helps

      Reply
      • Mattieu
        Posted on January 18, 2016 at 19:30 Permalink

        Thanks for your reply, I tried with your solution, but it doesn’t work fine… the menu a get the class but only for a few seconds… the classe change when the div appears, and briefly disappears when scrolling… is it possible for you to have a look ? would help ! if not I will have to find another solution but your plugin is really perfect for what I’m doing ! thanks a lot for your time and help !

        Reply
        • malihu
          Posted on January 19, 2016 at 00:45 Permalink

          The menu item gets the class when the target div appears in scrolling viewport. The class is removed when the target div gets out of the scrolling viewport. Isn’t this the case?

          I’ve made tests and the above behavior should happen. If it’s not I’d have to see your page/code in order to help.

          Reply
          • Mattieu
            Posted on January 19, 2016 at 14:42 Permalink

            Hello

            thanks for your reply.
            no it’s not the case.
            how can I send you my website adress ? I would like to keep it private.
            please let me know !
            thanks a lot

            Mattieu

        • malihu
          Posted on January 19, 2016 at 23:54 Permalink
          • [email protected]
            Posted on February 27, 2017 at 12:48 Permalink

            $("#some-id").is(":mcsInView"))
            return allways false;
            what could be wrong?

      • MAx Max
        Posted on February 22, 2017 at 16:33 Permalink

        if($("#some-id").is(":mcsInView")){
        allways false;
        what could be wrong?

        Reply
        • Loyal90
          Posted on March 16, 2017 at 05:17 Permalink

          Thank you and please help me at this point:
          I put this below code in my website but it always return false for everycase:

          if($(“#id1”).is(“:mcsInView”)) {

          }
          if($(“#id2”).is(“:mcsInView”)) {

          }

          Reply
  13. Kuba Fencl
    Posted on November 27, 2015 at 17:57 Permalink

    Saved my day 🙂 thanks

    Reply
  14. invsm
    Posted on October 21, 2015 at 22:22 Permalink

    Hi!
    scrollTo (by id) does not always scroll to the top of the element. Sometimes it stops a few px under or above the element.
    What could be the reason?

    Reply
    • malihu
      Posted on October 22, 2015 at 00:53 Permalink

      Either the “time” of triggering the scrollTo method (e.g. is all content fully loaded?) or maybe some CSS rule… I can’t really be sure without seeing it though.

      Reply
  15. sardaukar
    Posted on September 22, 2015 at 18:35 Permalink

    hi there,
    I’m just trying to add your custom scrollbar at my sidr UL elements, and it Works, but I want to hide the body scrollbar, because now, i have two, the customized, placed and displayed as desired, but the base scroll bar appears at the sidr side.

    i’ve search around about how to hide the body scrollbars and i’ve tried setting the overflow property to hidden (Chrome), but what it hiddens was the custom one, not the base one.

    I know that you custom bars are prepared to work under a custom región or div, but I don’t know if what I’m trying to achieve is possible or not.

    kind regards.

    Reply
    • malihu
      Posted on September 22, 2015 at 18:43 Permalink

      Hi, can you send me a link or a test page?

      Reply
      • sardaukar
        Posted on September 22, 2015 at 19:19 Permalink

        hi malihu,
        the following code is the a small demo of what i have. i’d noticed that if I remove the “divlabel” DIV, all works fine, but i don’t understand why.

        <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>test sidr</title> <link href="css/jquery.sidr.dark.css" rel="stylesheet" /> <link href="css/bootstrap.css" rel="stylesheet" /> <link href="css/jquery.mcustomscrollbar.css" rel="stylesheet" /> <style type="text/css"> .content { width: 90%; height: 100%; } #search-results-wrapper { margin: 10px 10px 10px 10px; } #divlabel { background-color: red; } </style> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.sidr.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/jquery.mcustomscrollbar.concat.min.js"></script> </head> <body > <div id="bodyDIV"> <div class="top-bar-buttons"> <a id="sidr-toggle" href="#sidr" >Toggle Sidr</a> </div> <div id="sidr-right" style="width:350px" > <div id="divlabel"> <label >MY LABEL IN ANOTHER DIV:</label> </div> <div id="search-results-wrapper" class="content mCustomScrollbar"> <div id="search-results"> <ul> <li id="result-01"><a href="#">Resultat 01</a></li> <li id="result-02"><a href="#">Resultat 02</a></li> <li id="result-03"><a href="#">Resultat 03</a></li> <li id="result-04"><a href="#">Resultat 04</a></li> <li id="result-05"><a href="#">Resultat 05</a></li> <li id="result-06"><a href="#">Resultat 06</a></li> <li id="result-07"><a href="#">Resultat 07</a></li> <li id="result-08"><a href="#">Resultat 08</a></li> <li id="result-09"><a href="#">Resultat 09</a></li> <li id="result-10"><a href="#">Resultat 10</a></li> <li id="result-11"><a href="#">Resultat 11</a></li> <li id="result-12"><a href="#">Resultat 12</a></li> <li id="result-13"><a href="#">Resultat 13</a></li> <li id="result-14"><a href="#">Resultat 14</a></li> <li id="result-15"><a href="#">Resultat 15</a></li> <li id="result-16"><a href="#">Resultat 16</a></li> <li id="result-17"><a href="#">Resultat 17</a></li> <li id="result-18"><a href="#">Resultat 18</a></li> <li id="result-19"><a href="#">Resultat 19</a></li> <li id="result-20"><a href="#">Resultat 20</a></li> </ul> </div> </div> </div> <script> $(document).ready(function () { $('#sidr-toggle').sidr({ name: 'sidr-right', side: 'left' }); $("#search-results").mCustomScrollbar({ scrollButtons: { enable: true }, theme: "light-thick", scrollbarPosition: "outside" }); }); </script> </div> </body> </html>

        Reply
        • sardauka
          Posted on September 22, 2015 at 19:26 Permalink

          nevermind… i’ve found what happens. it was my foult. i only had to add the overflow:hidden to my sidr style… 🙁

          sorry for wasting your time, and mine… 🙁 i was blind, there are no more reasons…

          Reply
          • malihu
            Posted on September 22, 2015 at 19:49 Permalink

            No problem, happens to me all the time 🙂

  16. Kenn
    Posted on August 17, 2015 at 19:54 Permalink

    Hi Manos,

    thanks for the great plugin. I am struggling for a combination of the method for id attributes on the same page (as explained in this article) and the explanation you gave to francois (above my comment) for ID attributes on other pages. I believe I need a modification of the code above that works for something like:

    Go to #id

    Basically I am trying to only have one menu for all the pages, so i need to have that foo.html in front of the ID.

    Thank you and please keep up the good work.

    Reply
    • Kenn
      Posted on August 17, 2015 at 19:56 Permalink

      sorry, sucked the code. I meant

      <a href="f00.html#id">Go to #id</a>

      Reply
    • malihu
      Posted on August 20, 2015 at 02:36 Permalink

      You’ll have to add a script that scrolls to location hash (e.g. #whatever) on page load. It gets a bit complicated when you want to use standard hashes because you need to prevent the browser from immediately jumping to the id.

      I’m posting a script example:

      (function($){ var hash=window.location.hash, //get the hash (e.g. #id) href=window.location.href.replace(/#.*$/,""); //get self URL without the hash (e.g. foo.html) $(document).ready(function(){ //prevent browser jump to hash/id if(hash){ $(window).scrollTop(0).scrollLeft(0); if(window.history && window.history.pushState){ window.history.pushState("","",href); }else{ window.location.href=href; } } }); $(window).load(function(){ //call plugin to your element (e.g. .content) $(".content").mCustomScrollbar(); //scroll to location hash if(hash){ var target=$(hash).parents(".mCustomScrollbar"); if(target.length){ target.mCustomScrollbar("scrollTo",hash); } } }); })(jQuery);

      Reply
      • Kenn
        Posted on August 26, 2015 at 14:20 Permalink

        It worked almost perfect on localhost with all the content in the cache, now that it is up I have two problems:

        There are pictures with unspecific height on the pages. When I click a link with a hash on another page, it scrolls to the location but minus the height of these pictures. I could give the pictures a specific height, but that would make it more difficult for others to update the content. Is there a way to kind of “delay” the scrollto till everything is loaded?

        And on this page I got two interactive google maps. They seem to impair the scrollto location hash totally when navigating from another page.

        I guess it´s both kind of the same problem.

        I would be grateful for any suggestions.

        Reply
        • malihu
          Posted on September 12, 2015 at 14:07 Permalink

          I haven’t being able to reproduce the issue with the non-cached images (tested it on Chrome, Firefox and IE). It seems to be scrolling to the “correct” position.

          The scrollTo event is already called when everything is loaded (called within $(window).load()) but you could add an extra delay if you want by adding a timeout, e.g. 300 milliseconds:

          setTimeout(function(){ target.mCustomScrollbar("scrollTo",hash); }, 300);

          Reply
  17. Patrik Lindström
    Posted on May 9, 2015 at 20:48 Permalink

    Hi! How would this script work if I want to have it on document ready? So when document is ready, it scroll down to the div id?

    Thanks!

    Reply
    • malihu
      Posted on May 9, 2015 at 21:43 Permalink

      Can you provide an example of what you want to do? Scroll to address bar hash or?

      Reply
  18. François
    Posted on May 1, 2015 at 19:59 Permalink

    Hello there,

    How about when the link is on another web page ?

    For example, smalltest.html#p2 on a specific page, let’s say test.html

    and on smalltest.html

    How can I make it so it uses your plugin to scroll and not the default browser one ?

    Reply

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