What's wrong with the jQuery code I wrote?

0

Hello, friends! I'm new to programming, and would like help identifying a problem in building a code to create a "Go to the top of the page" animation button in jQuery.

What I wrote seems correct, but once it is fired once, the scroll bar sticks to the top and does not come out anymore.

Follow the excerpts from HTML, CSS and JQUERY for review:

HTML

<button id="bt-top" type="submit" title="Vá para o topo da página │ Vaya a la parte superior de la página │ Aller en haut de la page"> ▲ </button>

CSS

#bt-top {
display: none;
position: fixed;
font-size: 18pt;
bottom: 12px;
right: 12px;
color: #fff;
border: solid 3px #fff;
background-color: #00b7ce;
cursor: pointer;
padding-bottom: 6px;
/* - - - - - - - - - */
border-radius: 12px; /* CSS3 */
    -moz-border-radius: 12px; /* Firefox */
        -webkit-border-radius: 12px; /* Chrome, Safari */
/* - - - - - - - - - */
width: 54px;
z-index: 999; }

#bt-top:hover { background-color: #6b6b6b; }

JQUERY

$(document).ready(function(){

$(window).scroll(function() {

    if ($(window).scrollTop() > 100) 
    {

        $("#bt-top").css({"display" : "block"});
    } 
    else 
    {
        $("#bt-top").css({"display" : "none"});
    }

    $("#bt-top").click(function() {
        $("html, body").animate({scrollTop: $("#principal").offset().top}, 2400);

    }); }); });

Thanks in advance for your help,

Alexandre Soares

    
asked by anonymous 22.08.2018 / 01:46

1 answer

0

It turns out that you are creating a new event every time the scroll bar is used. As the amount of events created is high, then the code will keep repeating the same process (from page to top) over and over again.

Example:

$(document).ready(function() {

  $(window).scroll(function() {

    if ($(window).scrollTop() > 100) {

      $("#bt-top").css({
        "display": "block"
      });
    } else {
      $("#bt-top").css({
        "display": "none"
      });
    }


  });
});

/* É necessário deixar o código abaixo fora do evento 'scroll' */
$("#bt-top").click(function() {
  $("html, body").animate({
    scrollTop: $("#principal").offset().top
  }, 2400);
});
div {
  height: 1000px;
}

button {
  position: fixed;
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="principal">
<button id="bt-top">Topo</button>

<div></div>
</div>
    
22.08.2018 / 01:55