Code Snippet: Keep Sidebar Elements in View When Scrolling

Goksel
goksel
Published in
2 min readAug 27, 2012

Whether it is a list of products you are promoting, published ads or other elements on the sidebar, you will likely want to have these elements in view at all times even when scrolling. By using JQuery, you can make this possible.

To do this, use the code snippet below:

//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);

The above code can also be made into a JQuery plug-in and used on WordPress sites.

Here is the plug-in version of the above code:

/**
* 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);
Remember to define the element you want to keep in view in the code by changing the ‘#sidebar-ads’ element to your preferences.Note that the plug-in only works on scroll down elements.Check out the demo page below that has been created using the above code:http://www.jquery4u.com/

--

--