Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate scrolltop on Opera bug

Has anyone tried using

$(“html, body”).animate({scrollTop:0}, 'slow');

on Opera browser?

It does a weird effect especially if you scroll on a long page, it seems like the page go first to the top and then it scroll down to the right point. It is a weird disturbing effect...

Is there any workaround to fix it? thanks

like image 241
Francesco Avatar asked Feb 02 '11 22:02

Francesco


2 Answers

The attribute was not defined properly in the past. It was introduced by IE, I think, then reverse engineered to be implemented by different user agents. It has been since described in CSSOM (still a working draft). As of today, there is still a bug indeed in Opera which is being in the process to be fixed.

## Possible hack.

A solution will be

$(window.opera?'html':'html, body').animate({ 
  scrollTop:0}, 'slow' 
);

Be careful because if Opera fixes it at a point, the code is likely to behave strangely.

Why?

  • In Firefox and IE quirks mode, you have to set the property on the "body" to make the page scroll, while it is ignored if you set it on the "html".
  • In Firefox and IE standards mode, you have to set the property on the "html" to make the page scroll, while it is ignored if you set it on the "body".
  • In Safari and Chrome, in either mode, you have to set the property on the "body" to make the page scroll, while it is ignored if you set it on the "html".

Since the page is in standards mode, they have to set it on both the "html" and "body, or it won't work in Safari/Chrome.

Now here's the bad news; in Opera, when you read the scrollTop of the body it is correctly 0, since the body is not scrollable within the document. But Opera will scroll the viewport if you set the scrolling offset on either the "html" or "body". As a result, the animation sets two properties, once for the "html" and once for the "body". The first starts at the right place, while the second starts at 0, causing the flicker and odd scroll position.

Better solution not involving user agent sniffing

From http://w3fools.com/js/script.js

    // find out what the hell to scroll ( html or body )
    // its like we can already tell - spooky
    if ( $docEl.scrollTop() ) {
        $scrollable = $docEl;
    } else {
        var bodyST = $body.scrollTop();
        // if scrolling the body doesn't do anything
        if ( $body.scrollTop( bodyST + 1 ).scrollTop() == bodyST) {
            $scrollable = $docEl;
        } else {
            // we actually scrolled, so, er, undo it
            $body.scrollTop( bodyST - 1 );
        }
    }
like image 167
karlcow Avatar answered Dec 02 '22 07:12

karlcow


This http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html#opera might be a better solution without using any Opera specific functions and accounting for quirks mode.

like image 44
Divya Manian Avatar answered Dec 02 '22 07:12

Divya Manian