Search code examples
javascriptjqueryscrollsmoothing

What script should i use to have smooth anchor scroll? None of my tried ones work


I am trying to insert smooth scroll to anchor links in the same page script into my web, but that doesn't seem to work. I tried a few of them but none works...

Here are some of them which I tried:

Best way to smooth scrolling to an internal link

http://css-tricks.com/snippets/jquery/smooth-scrolling/

Smooth scrolling when clicking an anchor link

http://www.sycha.com/jquery-smooth-scrolling-internal-anchor-links http://www.ezmacwebdesign.com/Demo/smooth-scroll.html

Maybe I am doing something wrong? I am inserting these scripts to the <head> part in between <script> </script>, I am very new to this and I know almost nothing about js and jQuery...

I also have this script in my head section which sticks my header to the top while scrolling, maybe it is causing the trouble?

<script> $(function(){
        var stickyHeaderTop = $('#headertop').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#headertop').css({position: 'fixed', top: '0px'});
                        $('#headeralias').css('display', 'block');
                } else {
                        $('#headertop').css({position: 'static', top: '0px'});
                        $('#headeralias').css('display', 'none');
                }
            });
        });
</script>

The link:

<a href="#vlog"> <div class="hbutton">Vlog</div> </a>

place where it should link to:

<a name="vlog" id="vlog"><div id="vlog"></div></a>

looking forward for help :)


Solution

  • Did you include the script required for scrolling as well?

    If not, add this code also in your script tag along with your other js code and try:

      $(document).ready(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;
                }
            }
        });
    });