Skip to content

Instantly share code, notes, and snippets.

@xavi-
Created January 18, 2011 17:58
Show Gist options
  • Save xavi-/784841 to your computer and use it in GitHub Desktop.
Save xavi-/784841 to your computer and use it in GitHub Desktop.
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( isScrollTop, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if( val === undefined ) {
elem = this[ 0 ];
if( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return !win ? elem[ method ] :
("pageXOffset" in win) ? win[ isScrollTop ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!isScrollTop ? val : jQuery( win ).scrollLeft(),
isScrollTop ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
diff --git a/src/offset.js b/src/offset.js
index 8696c20..7a235a9 100644
--- a/src/offset.js
+++ b/src/offset.js
@@ -257,7 +257,7 @@ jQuery.fn.extend({
// Create scrollLeft and scrollTop methods
-jQuery.each( ["Left", "Top"], function( i, name ) {
+jQuery.each( ["Left", "Top"], function( isScrollTop, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
@@ -271,10 +271,9 @@ jQuery.each( ["Left", "Top"], function( i, name ) {
win = getWindow( elem );
// Return the scroll offset
- return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
- jQuery.support.boxModel && win.document.documentElement[ method ] ||
- win.document.body[ method ] :
- elem[ method ];
+ return !win ? elem[ method ] :
+ ("pageXOffset" in win) ? win[ isScrollTop ? "pageYOffset" : "pageXOffset" ] :
+ jQuery.support.boxModel && win.document.documentElement[ method ] || win
}
// Set the scroll offset
@@ -283,8 +282,8 @@ jQuery.each( ["Left", "Top"], function( i, name ) {
if ( win ) {
win.scrollTo(
- !i ? val : jQuery( win ).scrollLeft(),
- i ? val : jQuery( win ).scrollTop()
+ !isScrollTop ? val : jQuery( win ).scrollLeft(),
+ isScrollTop ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
@xavi-
Copy link
Author

xavi- commented Jan 18, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment