What’s wrong with the jQuery code I wrote?

Asked

Viewed 35 times

0

Hey there, fellas! I am new to programming, and would like help to identify a problem in building a code to create a button "Go to the top of the page" with animation in jQuery.

What I wrote seems correct, but after it is triggered once, the scroll bar gets grabbed at the top and no longer comes out.

Follow the snippets of HTML, CSS and JQUERY for analysis:

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 for your help,

Alexandre Soares

  • Can use $("#bt-top").show() to display and $("#bt-top").hide() to hide.

  • Thank you! I will test this possibility! Thanks!

1 answer

0


Turns out you’re creating a new event every time the scroll bar is used. Since the number of events created is high, then the code will be repeating the same process (to take the page to the top) several times.

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>

<div id="principal">
<button id="bt-top">Topo</button>

<div></div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.