JavaScript
Article
By Sam Deering

jQuery Keep Element in View When Scrolling

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

stays-in-view

Demo

Scroll down this page and look at the right hand sidebar.

--ADVERTISEMENT--

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);
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?