Skip to content

Instantly share code, notes, and snippets.

@banago
Created August 24, 2012 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save banago/3451065 to your computer and use it in GitHub Desktop.
Save banago/3451065 to your computer and use it in GitHub Desktop.
Keep Elements in View When Scrolling
//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);
/**
* 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