0

I have a problem that I write the following code in the functions.php to realize the page go top.

It works.but just work for the user fist visit the page and click the button for first time.

I must refresh the page let the function work.

Did I miss something?

function back_and_top( $content ) {

    if( is_front_page() || is_home() ) {
    return $content;
}


    $custom_content .= '<div class="back_and_top">
<a class="top_btn" href="javascript:const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
scrollToTop();" title="go top"><i class="fa fa-sort" aria-hidden="true"></i>Go Top</a>

</div>';

    $content .= $custom_content;
    return $content;
}
add_filter( 'the_content', 'back_and_top' );

closed as off-topic by Jacob Peattie, Krzysiek Dróżdż, Tom J Nowell Jan 3 at 13:24

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

1

If you had checked the JS console, then you would see this error:

Uncaught SyntaxError: Identifier 'scrollToTop' has already been declared at :1:1

And that's the reason, why your code works only once.

Don't put this as inline JS. Write it correctly.

In go-to-top.js file:

jQuery(function ($) {

    $('.go-to-top').click(function (e) {
        e.preventDefault();
        c = document.documentElement.scrollTop || document.body.scrollTop;
        if (c > 0) {
            window.requestAnimationFrame(scrollToTop);
            window.scrollTo(0, c - c / 8);
        }
    });

});

And in your PHP file:

function back_and_top( $content ) {

    if ( is_front_page() || is_home() ) {  // I'm pretty sure that's not enough (there are archives and so on)
        return $content;
    }

    $custom_content = '<div class="back_and_top">
<a class="go-to-top" href="#" title="go top"><i class="fa fa-sort" aria-hidden="true"></i>Go Top</a></div>';

    $content .= $custom_content;
    return $content;
}
add_filter( 'the_content', 'back_and_top' );
  • If I want to add go-to-top js code to my function.php,Is it possible to achieve it? Because I want to put all code in the functions.php ! That`s convenient to manage. – Kenny Jan 3 at 13:20
  • 1
    JS code should be in JS files not as inline code in PHP files - that’s not easier to manage - that’s a mess... – Krzysiek Dróżdż Jan 3 at 13:21

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