0

I have the following script that provides an anchor effect:

// Smooth scrolling when clicking on a hash link
    $('a[href*="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        if ($(window).width() > 1023) {
            var $scrollTop = $target.offset().top - 120;
        } else {
            var $scrollTop = $target.offset().top;
        }

        $('html, body').stop().animate({
            'scrollTop': $scrollTop
        }, 900, 'swing');
    });

The problem is that this only works on home page, but in the other pages it does not work because I need to provide the web link (www.url.com/#anchor). But if I do this, the effect does not apply. someone knows how to add to the effect, for example get_site_url ('/#anchor/'); , and so this always take the url of the web as a base?

I hope I have expressed myself well. Greetings and thanks

1

CSS now has the property scroll-behavior (browser support is there but not so great). You can use it as described here:

html {
  scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) {
  html {
    scroll-behavior: auto;
  }
}

If this doesn't work for you, you're stuck with JS. The problem is, on a new page load, browsers automatically jump to the position of the fragment. But there is a workaround as described in this StackOverflow answer:

// to top right away
if (window.location.hash) scroll(0,0);
// void some browsers issue
setTimeout(function() { scroll(0,0); }, 1);

$(function() {
    // *only* if we have anchor on the url
    if(window.location.hash) {
        // smooth scroll to the anchor id
        $('html, body').animate({
            scrollTop: $(window.location.hash).offset().top + 'px'
        }, 1000, 'swing');
    }

});
  • 1
    Wow, The CSS option works perfectly. One more question, is the first time I use an anchor effect and now the problem is that it slides under the title because I have a sticky menu, how could I fix this bug? Thank you – Dario B. Jul 24 at 11:49
  • @DarioB. You can do this in JS, but there is also a pure CSS way: :target. The WordPress Docs uses this mechanism, just inspect the headline and you'll see padding-top and negative margin-top – kero Jul 24 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.