Taking Jquery to Run

Asked

Viewed 185 times

2

$(window).scroll(function () {

    if ($(this).scrollTop() > 0) {

        $('#header ul').animate({ width: 811, marginTop: 0 }, 200);
        $('#inicio-btn, #sobre-nos-btn, #sistemas-btn, #noticias-btn, #contato-btn, #usuario-btn').animate({ marginTop: 30 }, 200);
        $('#logo').animate({ width: 120, marginTop: 18 }, 200);

    } else {

        $('#header ul').animate({ width: 931, marginTop: 90 }, 200);
        $('#inicio-btn, #sobre-nos-btn, #sistemas-btn, #noticias-btn, #contato-btn, #usuario-btn').animate({ marginTop: 37 }, 200);
        $('#logo').animate({ width: 240, marginTop: 0 }, 200);

    }

});

When the condition is false, that is, when you go back to the top of the page, the code takes a while to run. It’s like JQ just sits there thinking about what to do... I’ve tried a thousand things and nothing solves this problem.

  • Ever tried to put .stop() before the .animate()?

  • 1

    Referencing selectors may also be a good practice to prevent jQuery at all times search for the element in DOM

  • You can reproduce this strange behavior in a jsFiddle?

  • @Wallacemaxters own jquery has internal cache, referencing can help improve some milesegundos, but nothing noticeable to use :) jquery is a bit buggy but it is very useful

1 answer

3

The problem may be caused by the lack of stop before the animations.

Try to put your code this way:

$(window).scroll(function () {

    if ($(this).scrollTop() > 0) {

        $('#header ul').stop().animate({ width: 811, marginTop: 0 }, 200);
        $('#inicio-btn, #sobre-nos-btn, #sistemas-btn, #noticias-btn, #contato-btn, #usuario-btn').stop().animate({ marginTop: 30 }, 200);
        $('#logo').stop().animate({ width: 120, marginTop: 18 }, 200);

    } else {

        $('#header ul').stop().animate({ width: 931, marginTop: 90 }, 200);
        $('#inicio-btn, #sobre-nos-btn, #sistemas-btn, #noticias-btn, #contato-btn, #usuario-btn').stop().animate({ marginTop: 37 }, 200);
        $('#logo').stop().animate({ width: 240, marginTop: 0 }, 200);

    }

});

Browser other questions tagged

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