Created
August 24, 2012 14:13
-
-
Save banago/3451065 to your computer and use it in GitHub Desktop.
Keep Elements in View When Scrolling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//keep element in view | |
(function($) | |
{ | |
$(document).ready( function() | |
{ | |
var elementPosTop = $('#sidebar-ads').position().top; | |
$(window).scroll(function() | |
{ | |
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height(); | |
//if top of element is in view | |
if (wintop > elementPosTop) | |
{ | |
//always in view | |
$('#sidebar-ads').css({ "position":"fixed", "top":"10px" }); | |
} | |
else | |
{ | |
//reset back to normal viewing | |
$('#sidebar-ads').css({ "position":"inherit" }); | |
} | |
}); | |
}); | |
})(jQuery); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jQuery keep element in view plugin. | |
* | |
* @author David Gitonga | |
* @copyright Copyright (c) 2012 DeveloperDrive | |
* @license Licensed | |
* @link http://developerdrive.com | |
* @since Version 1.0 | |
* | |
*/ | |
(function($) | |
{ | |
$.fn.keepElementInView = function() | |
{ | |
var elemPosTop = this.position().top; | |
$(window).scroll(function() | |
{ | |
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height(); | |
if (wintop > elemPosTop) | |
{ | |
this.css({ "position":"fixed", "top":"10px" }); | |
} | |
else | |
{ | |
this.css({ "position":"inherit" }); | |
} | |
}); | |
return this; | |
}; | |
$(document).ready( function() | |
{ | |
jQuery('#sidebar-ads').keepElementInView(); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment