scroll to anchor not working on WordPress page

From this answer, I found the code to animate the scroll to any anchors here.

The site in question is WordPress, so I replaced $ with jQuery:

Read More
jQuery(document).ready(function() {
    jQuery('a[href^="#"]').on('click', function(event) {
        var target = $(this.href);
        if( target.length ) {
            event.preventDefault();
            jQuery('window').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    }
});

Edited thanks to A Wolff.

However, clicking the anchors at the top of the content on this page does not scroll the movement to the anchor, it still moves instantly on click.

e.g. links that don’t scroll to anchors:

  • PERSONAL ASSISTANTS
  • AFTER SALES SERVICE etc.

Assistance appreciated.

Related posts

Leave a Reply

2 comments

  1. This work!

    jQuery('a[href^="#"]').on('click', function(event) {
        event.preventDefault();
    
        var anch = this.href.match(/#[a-zA-Z0-9-_]+/i),
            target = jQuery(anch[0]);
    
        if( target.length ) {
    
            jQuery('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    });
    
  2. Binding every anchor with scroll event sounds kinda bad imo.

    Why don’t you add .scroll class on the scrollable links and execute the script only on that class? What if you want to link to an outside content? If you have made every link scrollable, you won’t be able to open it normally, breaking the natural usage of the links.

    I like to add .scroll class on the links that should scroll somewhere and use

    $(".scroll").on('click', function(e){
        e.preventDefault();
        var href = $(this).attr('href');
        var hash = href.split('#');
        var url_hash = '#' + hash[1];
        if ($(url_hash).length > 0) {
            var offset = ($(window).width()<769) ? 20 : 65;
            $('html, body').animate({
                scrollTop: $(url_hash).offset().top-offset
            }, 1000);
        } else{
            location.href = href;
        }
    });
    

    This way your normal links that should point to another page, or outside content will still work.

    Just a suggestion 🙂