Welcome to WebmasterServe!

FREE TO JOIN! Join us now to engage in informative and friendly discussions about Webmastering, SEO, SEM, Internet Marketing, Programming, Graphic Design, Online Jobs and more. What are you waiting for? Ready to join our friendly community? It takes just one minute to register.

Dismiss Notice

Join WebmasterServe Forums 
Join the discussion! Have a better idea or an opinion? It takes just one minute to register Click Here to Join

Help Me/Question Jquery Smooth Scrolling

Discussion in 'Javascript and jQuery' started by PrashantD, Jan 16, 2016.

  1. PrashantD

    Yellow Belt

    Joined:
    Dec 7, 2015
    Messages:
    132
    Ratings:
    +24 / -0
    I have various internal links like in the HTML example below, and I've used a little bit of jQuery to scroll "smoothly" to the target.

    The HTML:
    HTML:
    Select All
    <a href="home.php#contact">Contact</a> . . . <a id="contact"></a>
    jQuery:
    Code:
    Select All
    var $root = $('html, body'); // Caching the selector, so that it doesn't run every single time an anchor is clicked. $('a[href*="#"]:not([href="#"])').on('click', function(event){ event.preventDefault(); // Prevent the "normal" behaviour which would be a "hard" jump. var target = this.hash; var $target = $(target); $root.stop().animate({ scrollTop: $target.offset().top-55 }, 900, 'swing', function () { window.location.hash = target; }); });
    I am trying to preserve the location in the address bar e.g. "www.mydomain.com/#contact", however, the line "window.location.hash = target;" is somehow nullifying the vertical offset "top - 55".

    Any ideas?
     
  2. Oldwriter

    Yellow Belt

    Joined:
    Dec 10, 2015
    Messages:
    64
    Ratings:
    +28 / -0
    Hello dear @PrashantD@PrashantD

    Save and upload this to your site:

    Code:
    Select All
    /*-------------------------------------------------------------------------- * Smooth Scroller Script, version 1.0.2 * (c) 2007 Dezinerfolio Inc. <midart@gmail.com> * Edited by @floorish * * For details, please check the website : http://dezinerfolio.com/ * --------------------------------------------------------------------------*/ Scroller={speed:10,offset:0,gy:function(e){var o=e.offsetTop;if(e.offsetParent)for(;e=e.offsetParent;)o+=e.offsetTop;return o-this.offset},scrollTop:function(){var e=document.body,o=document.documentElement;return e&&e.scrollTop?e.scrollTop:o&&o.scrollTop?o.scrollTop:window.pageYOffset?window.pageYOffset:0},add:function(e,o,r){return e.addEventListener?e.addEventListener(o,r,!1):e.attachEvent?e.attachEvent("on"+o,r):void 0},end:function(e){return window.event?(window.event.cancelBubble=!0,void(window.event.returnValue=!1)):void(e.preventDefault&&e.stopPropagation&&(e.preventDefault(),e.stopPropagation()))},scroll:function(e){var o=window.innerHeight||document.documentElement.clientHeight,r=document.body.scrollHeight,t=Scroller.scrollTop();o>r-e&&(e=r-o);var n=(e-t)/Scroller.speed;n=e>t?Math.ceil(n):Math.floor(n),t+=n,window.scrollTo(0,t),Scroller.previousPos=t,(t==e||0==n)&&(clearInterval(Scroller.interval),Scroller.previousPos=!1)},init:function(){Scroller.add(window,"load",Scroller.render)},render:function(){Scroller.end(this);for(var e=document.getElementsByTagName("a"),o=0;o<e.length;o++){var r=e[o];!r.href||-1==r.href.indexOf("#")||r.href.indexOf("#")==r.href.length-1||r.pathname!=location.pathname&&"/"+r.pathname!=location.pathname||Scroller.add(r,"click",function(){Scroller.end(this);var o=this.getAttribute("href").split("#")[1],r=document.getElementById(o);if(!r)for(var t=0;t<e.length;t++)if(console.log("name",name),e[t].name==o){r=e[t];break}r&&(clearInterval(Scroller.interval),Scroller.interval=setInterval(function(){Scroller.scroll(Scroller.gy(r))},10))})}}},Scroller.init();
    (Source)

    Use the file name "smooth-scroll.min.js", then add it to your page's html:

    HTML:
    Select All
    <script type="text/javascript" src="smooth-scroll.min.js"></script>
    And that's it!

    Now you can add your links as usual and they'll have the effect you want:

    HTML:
    Select All
    <a href="#contact">Contact</a> . . . <a name="contact"></a>
    No jQuery required.

    Cheers!
     
    • Informative Informative x 1
    • List
  3. PrashantD

    Yellow Belt

    Joined:
    Dec 7, 2015
    Messages:
    132
    Ratings:
    +24 / -0
    Thanks Oldwriter. This is just what I was looking for. Using it on the page, and it works perfectly! Just out of curiosity, is there any way to achieve this by using the jQuery above?
     
  4. Oldwriter

    Yellow Belt

    Joined:
    Dec 10, 2015
    Messages:
    64
    Ratings:
    +28 / -0
    Hello again dear @PrashantD@PrashantD

    If you really want to do it via jQuery, you can use:

    HTML:
    Select All
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); </script>
    (Source)

    Hope it helps.
     

Share This Page