Search code examples
javascriptsidebarfloating

Javascript - Make div follow page ( works but it pushes sidebar too?)


/-----------------------------------------------------------------------------------/ EDIT: I do NOT want to use fixed CSS positioning. It's at the bottom of the viewport without scrolling, however I want it to follow when it gets to the top. /-----------------------------------------------------------------------------------/

I'm making a Squeeze Page with a MASSIVE sidebar. It's got tons of testimonials and facts and pictures and stuff. However, I have a button near the top I want to follow the user down the page as they scroll. Shouldn't be too hard right?

I've got this script - which starts dragging the .followme when it hits the top of the page. However - it also pushed down all the divs beneath it. Can I tell it to target JUST .follow and no affect the divs below it?

<script type="text/javascript">
var documentHeight = 0;
var topPadding = 15;
$(function() {
    var offset = $(".followme").offset();
    documentHeight = $(document).height();
    $(window).scroll(function() {
        var sideBarHeight = $(".followme").height();
        if ($(window).scrollTop() > offset.top) {
            var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
            var maxPosition = documentHeight - (sideBarHeight + 100);
            if (newPosition > maxPosition) {
                newPosition = maxPosition;
            }
            $(".followme").stop().animate({
                marginTop: newPosition
            });
        } else {
            $(".followme").stop().animate({
                marginTop: 0
            });
        };
    });
});


Solution

  • You have an easier option which doesn't require any JS\jQuery at all.

    .followme {
        position: fixed;
        height: 30px;
        width: 30px;
        background-color: #FF0000;
        top: 48%;
        left: 0;
    }
    

    This will never affect any of the other elements of the page and doesn't require any scripting at all. Now if you need the element (followme) to for example show at a certain scroll % or any other interactivity you might think of, then you will be needing to think more creatively. But if the problem is just to let the element follow your scrolling then the above should be a good and clean solution.

    Example code:

    http://jsfiddle.net/bhpgC/