Insert variable in jquery Animate value

Asked

Viewed 65 times

3

I’m trying to insert this value in scrollTop but it’s not returning, some problem?

var top = $('.sku').offset().top;

$(window).animate({
    scrollTop: top
}, 500)
  • 1

    At what point are you initiating this variable top? make sure the element has already been rendered to pick up its position, otherwise it will always return 0.

  • @Brunoromualdo I am half lay in the subject, could give an example or some document for me to take a look?

  • 2

    You’re calling it inside a $(document).ready(function(){ ... }) or $(function(){ .. })?

  • That’s what it was, Thanks!

  • Whenever possible put your javascript at the end of the tag <body>, before her closure.

  • I already formulate a more explanatory answer for future research.

Show 1 more comment

2 answers

3


Make sure to pick up the position of the element after it has been rendered, see the example:

<head>
    ... estilos e tudo mais

    <script>
        var top = $("div").offset().top; // vai retornar 0, porque o elemento ainda não foi renderizado
    </script>

</head>

<body>

    <div style="top: 200px;">Teste</div>

    <script>
        var top = $("div").offset().top; // vai retornar o valor correto pois o elemento foi renderizado
    </script>

</body>

As best practices it is recommended to put the javascript (including the Imports) at the bottom of the page before closing the tag <body>, because the browser blocks rendering until these scripts are loaded:

<body>

    ... Seu conteudo html

    // Vai carregar  js depois que a pagina for renderizada
    <script type="text/javascript" src="arquivo.js"></script>
    <script>
        ... Seus scripts
    </script>

</body>

And yet you can use the Document.ready of Jquery to run a script only when the document is ready:

    <script>
         $(document).ready(function() {
              altert("pronto");
         })

         // ou a versão simplificada dele
         $(function() {
              altert("pronto");
         })

    </script>
  • Good!! Great!!!!

0

In principle the value must be passed correctly, however, the animation only seems to work if you use in $("html, body").

Thus

    var top = $(".sku").offset().top;
    $("html, body").animate({ scrollTop: top }, 500);
  • Hello good afternoon, the problem is that this example returns to the top as it returns value 0

  • 1

    There was a typo, missing the . in the $(".sku")

  • Opa yes! had put, but it is not the problem, it is as it did not take the value of the variable

  • What returns if you do $(".sku").length?

Browser other questions tagged

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