Steve Steve - 5 months ago 25
jQuery Question

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
:

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.

Answer

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);
    }
});