简体   繁体   中英

Scroll to Top jQuery

I am trying to create a super simple Scroll to top button.

It works but it's appending the button to the body every time when i scroll.

I would like to append it only once and fade it in and if you click it you will be scrolled back to the top off the page and it will fadeout.

The functionality is working but its appending it to the page in an loop.

I know it's a simple bug but, I can't figure it out.

My code:

$(window).scroll(function () {
    var scrollPosition = $(this).scrollTop();
    var to_top = '<a class="back-to-top" href="#"></a>';

    if (scrollPosition >= 500) {
        $("body").append(to_top);
        $('.back-to-top').fadeIn(1600);
    } else {
        $('.back-to-top').fadeOut(800);
    }

    $( ".back-to-top" ).on( "click", function(event) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, "slow");
    });
});

Well, you're telling it to append the every time the scroll event is fired, so check if it exists first, see if it works out for you.

$(window).scroll(function () {
  var scrollPosition = $(this).scrollTop();
  var toTops = $('.back-to-top'); // get jQ object once
      if (scrollPosition >= 500) {
        if (!toTops.length){ // if no elems

            // create one
            var $to_top = $('<a class="back-to-top" href="#"></a>');
            $to_top.on( "click", function(event) {
                event.preventDefault();
                $("html, body").animate({ scrollTop: 0 }, "slow");
            });

            // then attach it
            $("body").append($to_top);
        } else { 

           // if elems exist, fade them in
           toTops.fadeIn(1600);
        }

      } else {
        toTops.fadeOut(800);
      }


});

You should create button once and then hide/show it.

jQuery(function($) {
    var to_top = $('<a class="back-to-top" href="#"></a>'),
    visible = false;
    to_top.appendTo('body').hide();

    $( ".back-to-top" ).on( "click", function(event) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, "slow");
    });

    $(window).scroll(function () {
        if ($(this).scrollTop() >= 500)
            if(!visible){
                to_top.stop(true,false).fadeIn(1600);
                visible = true;
            }
        else
            if(visible){
                to_top.stop(true,false).fadeOut(800);
                visible = false;
            }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM