jQuery Keep Element in View When Scrolling
Share
Quick jQuery code snippet on how to keep an element in view. For demo scroll down on any page on the blog and see ads on right sidebar ads, they remain inview as you scroll down the page. Then go back to normal view when you scroll up again.
Demo
Scroll down this page and look at the right hand sidebar.
The Code
//keep element in view
(function($)
{
$(document).ready( function()
{
var elementPosTop = $('#jq4u-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
$('#jq4u-sidebar-ads').css({ "position":"fixed", "top":"10px" });
}
else
{
//reset back to normal viewing
$('#jq4u-sidebar-ads').css({ "position":"inherit" });
}
});
});
})(jQuery);
Turning it into a plugin
Could quite easily be made into a jQuery plugin. Actually I’ll code one out real quick and include it below.
/**
* jQuery keep element in view plugin.
*
* @author Sam Deering
* @copyright Copyright (c) 2012 jQuery4u
* @license http://jquery4u.com/license/
* @link http://jquery4u.com
* @since Version 1.0
* @notes Plugin only works on scroll down elements.
*
*/
(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('#jq4u-sidebar-ads').keepElementInView();
});
})(jQuery);