Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the screen from flickering right before jQuery's animate() executes

I have noticed that right before my scroll-to-top animation takes place, the screen flickers.
This can be seen live at: http://www.dreamtheater.co.il

To recreate:

  1. Scroll down until the menubar only remains at the top
  2. Click on the right-most link from the menu

The HTML's body is like so: <body id="top">.
And the JavaScript (relevant code at the very bottom):

$(function() {
    var stickyHeader = $('#menubar').offset().top;

    $(window).scroll(function() {
        if ($(window).scrollTop() > stickyHeader) {
            ...
            ...
            $("a[href='http://www.dreamtheater.co.il/index/']").attr('href', '#top');
        } else {
            ...
            ...
            $("a[href='#top']").attr('href', 'http://www.dreamtheater.co.il/index/');
        }
    });

    $('#top').on("click",function() {
        $('body,html').animate({ scrollTop: 0 }, 'slow')
    });
});
like image 943
Idan Adar Avatar asked Mar 23 '23 04:03

Idan Adar


1 Answers

Okay, seems the problem was two-folded:

  1. I pointed to <body id="top"> instead to the href, which I also dynamically change on scroll
  2. Did not 'release' the event

It now works smoothly, with no flickering, like this:

$("#menubar").on("click", "#menu a[href='#top']", function(){
    $('body,html').animate({ scrollTop: 0 }, 'slow');
    return false;
});
like image 192
Idan Adar Avatar answered Apr 05 '23 23:04

Idan Adar