• Resolved 凱寧

    (@kennyateam990)


    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' );
Viewing 6 replies - 1 through 6 (of 6 total)
  • Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    That’s really messy to read, can you show us the link on the page instead?

    Thread Starter 凱寧

    (@kennyateam990)

    why my code works only once ? that`s what I want to ask ~

    <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>

    the problem is this javascript code.did I miss anything??

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    I know what you asked. To answer you without reading your code, PHP functions only get ran on page load. That’s what server side languages do.

    • This reply was modified 7 years, 3 months ago by Andrew Nevins.
    Thread Starter 凱寧

    (@kennyateam990)

    oh,I see!!

    so how do I get page go top in the functions.php?

    I suspect that it only runs once because you are setting a constant to a value and then trying to overwrite it on subsequent clicks.

    Move the function outside of the click handler into a separate file or embedded into the page along with the rest of your javascript imports. Then reduce the click handler to a simple call of the function instead of recreating the function on every click.

    Unless there is some special need to write your own code, you can always try with a plugin…something like Scroll Top Advanced. Anyway, you can download it and check how it is done, but quick response is it can be done with JavaScript or JQuery.

Viewing 6 replies - 1 through 6 (of 6 total)

The topic ‘Go top smooth function’ is closed to new replies.