0

I would like to set a position fixed and relative. I have a large div for all my content. When i set the position of div inside to relative it aligns to the left of my content div. when i change that position to fixed it aligns to my browser side. I have been told that there is no css solution, but is there any other way.

basically im trying to get the same effect as the right hand bar on this website: http://www.nytimes.com/interactive/us/sept-11-reckoning/viewer.html

Code:

 #content{
 width: 1000px;
 margin-right: auto;
  margin-left: auto;
 }

  #text{
  position: fixed;
  }


  <div id='content'>
        <div id='text'>Welcome to the site</div>
  </div>
kirby
  • 3,785
  • 12
  • 38
  • 52

1 Answers1

1

The function isScrolledIntoView() used below is from another question Check if element is visible after scrolling

Explanation of Example

First off we have the function isScrolledIntoView() which simply returns true or false if an element is visible inside your browsers viewing area.

You need to use two divs or some kind of anchor point and a follow div. Your anchor div is used to determine when we should switch the follow div to a fixed style to follow on scrolling or switch back to an absolute position if the anchor is back in view to return the follow div to its original position on the page.

With your anchor point, following div, the function to check if an element is visible in the viewing area, we can make use of the jQuery .scroll() event binding method on the window to fire an event when the user scrolls on the page.

Example Script

$(window).scroll(function () {
    if (! isScrolledIntoView($('#anchor')))
    {
        // anchor div isn't visible in view so apply new style to follow div to follow on scroll
        $('#follow').css({ position: 'fixed', top: '10px' });
    }
    else
    {
        // anchor div is visible in view so apply default style back to follow div to place in default position
        $('#follow').css({ position: 'absolute', top: '100px' });
    }
});

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

Fiddle demo

Community
  • 1
  • 1
Jeff Wilbert
  • 4,190
  • 1
  • 18
  • 35